Python learning 3: List, tuples, and python learning list
1. List: 1. How to define a list:
list1 = [1,2,3,4,"hello","world"]
As shown above, list1 is a list. The content of the list is enclosed in brackets.
print(list1[2])
The value is calculated using the following table. The following table starts from 0, returns the subscript numbered 2, and the obtained value is 3.
2. Common List operations:
List1.append (5) # append an element
If you want to append multiple elements, You can append a list2 object, as shown below:
List2 = [1234, 6] list1.append (list2) for I in list1: print (I) print (list1) output:
Hello
World [3, 9, 5, 9, 8, 7, 6] [1, 2, 3, 4, 'Hello', 'World', [3, 9, 5, 9, 8, 7, 6]
From the example above, we can know that the list can have repeated elements and append another list to the list. However, you must note that even if you append another list, in list1, The append list is treated as an element, instead of appending each element in list2 to list1.
List1.clear (); # clear the current list print (list1)
Output:
[]
Print (list1.count ("hello") # calculate the number of times the current element appears. print result 1.
List2 = list1.copy () # copy a list. Note the difference between the list1 and the puttle value assignment. If we change list1, The list3 value also changes, that is to say, list1 and list3 are the same memory address, while list2 is a new memory address and will not be affected by list1 changes list3 = list1print (list2) print (list3)
List2 = ["cat", "dog"] # used to add another list. If the append cannot solve the problem, use extend to output the list1.extend (list2) print (list1): [1, 2, 3, 4, 'Hello', 'World', 'cat', 'Dog']
Print (list1.index ("hello") # obtain the following table where the current element is located, starting from 0. The print result is 4.
List1.insert (0, "a") # insert an element. The first parameter is the following table, and the second parameter is the print (list1) content to be inserted)
Output:
['A', 1, 2, 3, 4, 'Hello', 'World']
Print (list1.pop (4) # removes an element from the I list and returns the value of the removed element print (list1)
List1.remove (4) # remove an element. The parameter is the value of the parameter to be removed. list1.remove ("hello") print (list1) Outputs [1, 2, 3, 'World']
List1.reverse () # print (list1) output of the response sorting list: ['World', 'Hello', 4, 3, 2, 1]
2. tuples 1. How to define tuples
tuple2 = ("hello","world",2,8)
Unlike the list, the difference is that the list uses brackets [] to contain elements, while the tuples use parentheses.
Another definition method is to convert the list, as shown below:
tuple2 = tuple(list1)
Print all the elements of list1 in tuple2, but wrapped in parentheses.
The biggest difference between a tuple and a list is that the content cannot be changed. Once a tuple is defined, the value of this tuples cannot be changed until it is recycled.