python learning three: list, tuple

1. list:

1. Definition of list:

list1 = [1,2,3,4,"hello","world"]

As shown above, list1 is a list with contents in brackets


The value is obtained by using the following table, which starts from 0, takes the subscript No. 2, and takes the value of 3

2. Common operations of list:

list1.append(5) #Append an element

If you want to append multiple elements, we can append a list2, as follows

list2 = [3,9,5,9,8,7,6]
for i in  list1:

world [
3, 9, 5, 9, 8, 7, 6] [1, 2, 3, 4,'hello', 'world',[3, 9, 5, 9, 8, 7, 6]]

From the above example, we can see that a list can have duplicate elements, and another list can be appended to one list. But it should be noted that even if another list is appended, the appended list is treated as an element in list1, rather than every element in list2.

list1.clear(); #Clear current list

print(list1.count("hello")) #Calculate the number of times the current element appears, print result 1
list2 = list1.copy() #To copy a list, you need to pay attention to the difference between the direct assignment and the stool assignment. If we change list1,that list3 It will change, that is to say list1 And list3 Is the same memory address, and list2 Is a new memory address and will not receive list1 Impact of change
list3 = list1
list2 = ["cat","dog"]#Used to add another list, append Use of unsolvable problems extend that will do

[1, 2, 3, 4, 'hello', 'world', 'cat', 'dog']
print(list1.index("hello")) #Get 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. The second parameter is the content to be inserted

['a', 1, 2, 3, 4, 'hello', 'world']
print(list1.pop(4)) #Used to remove i An element in the list and returns the value of the removed element
list1.remove(4) #Remove element, parameter is the value of the parameter to be removed

[1, 2, 3, 'world']
list1.reverse() #Response sorting of lists

['world', 'hello', 4, 3, 2, 1]

2. tuple

1. Definition of tuples

tuple2 = ("hello","world",2,8)

Very similar to a list, the difference is that the brackets [] used in the list contain elements, while the tuples use brackets.

Another way to define it is to convert it from a list, as follows:

tuple2 = tuple(list1)

All the elements of list1 appear in tuple2 under printing, but they are wrapped by brackets ().

The biggest difference between a tuple and a list is that a tuple cannot change its content. Once a tuple is defined, it cannot change its value until it is recycled.

Tags: Python

Posted on Sun, 05 Apr 2020 10:04:33 -0700 by jdsflash