list list
A list is an ordered collection from which we can add and remove elements at will.
my_list = ['bob','anna','job']
my_list
This is how the list is defined using []
to define. We can use the len() function to get the length of the list elements.
access element of list
We get the child elements in the list by index, such as:
my_list = [‘bob’,’anna’,’job’]
my_list[0]
This will print out the string 'bob'. If it exceeds the range of the index, python will report IndexError: list index out of range
such an error to prompt the error. If you use the index with a negative sign from the back.
add elements to the list
We can use the append() method to append elements to the end of the list.
We can also use the insert() method to add elements to the indexed position, such as
my_list.insert(0,'poker')
my_list
['poker','pop','anna','job']
delete element from list
We use pop() to pop the element at the end of the list. To specify which element to delete, just add the index of the deleted element to pop().
Modify an element of the list
At this time, you need to assign the index to the list.
list can be nested
my_list = ['bob',['年后',454],'awdaw']
Nesting in this way is also allowed to access the same way of indexing
A tuple is also an ordered list
Note that the biggest difference between tuples and lists is that they are immutable
Since the element is immutable, there is no such method as append(), insert(), we also rely on the index to access, because it cannot be modified, this will make the code more secure, use ()
to define
It should be noted that when defining a tuple with only one element, remember to add
,
it to disambiguate
list and tuple are nested within each other
Pay attention to understanding that tuple is unchanged, and tuple points are never changed