“This is the fifth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
preface
The next two articles will cover mutable data types. This article will start with list, which is the most basic data type in Python. Its elements can be any Python data type
The list of
[] : int float STR list tuple dict Boolean; Different elements are separated by commas
Create a list of
str1="123"
list_1=[] # denotes an empty list
list_2=list(str1) # break the string into a list of elements []
print(list_2) ["1","2","3"]
Copy the code
Approaches to
- Value by index
- Supported slice values [m:n:k]
Add and delete
- Multiple ways to add, append append, append at the bottom of list
list1=[1.2.3.4]
list1.append("value") # append directly to the list,
print(list1) # output: [1,2,3,4,"value"]
Copy the code
- Insert Inserts an element at the specified subscript position, moving the element back from the original position
list1=[1.2.3.4]
list1.insert(2."element")
print(list1) # output: [1,2,"element",3,4]
Copy the code
- Extend (), which takes iterables such as set(), STR, tuple, list
list1=[1.2.3.4]
list1.extend("abc")
print(list1) # output: [1,2,3,4,"a","b","c"]
Copy the code
- Several ways to delete
pop() Delete the last element of the list
remove(element)Delete the first occurrence of the element
del list[1] Delete the element at index position of listing 1
clear() # Clear the list
Copy the code
- List [index_num]=New_value, where the index_num position is replaced with New_value
The sorting
- Ascending order. Note that ascending list elements must be of type int
list1=[5.2.3]
list1.sort() # default ascending order;
print(list1) # output: [2,3,5]
Copy the code
- Descending,sort, can be determined by argument, default is False ascending
list1=[5.2.3]
list1.sort(reverse=True)
print(list1) # output: [5,3,2]
Copy the code
- trans
list1=[1.2.3]
list1.reverse()
print(list1) # output: [3,2,1]
Copy the code
Other built-in functions
- All () # list returns false whenever there is one element in the list
- Any () # list returns true as long as there is one true in the list of elements
- Len () # Find the length of the list element
- Count () # Count the number of elements in the list
- Max () # returns the largest value in the list element
- Min () # returns the smallest value in the list element
A collection of
Set (), with curly braces {}, is used with the list type because it can be converted from list to list and has the property of de-duplicating list elements
Create the set() collection
s=set(a)# denotes an empty set
print(s) Output: set() Why not {}, because {} is a dict with no value
s=set([1.2.3])
print(s) {1,2,3}
Copy the code
Add elements if there are duplicate elements that are overwritten
se={1.2.3}
se.add(4)
print(se) {1,2,3,4}
Copy the code
- It is an immutable data type