list list
L = ['Adam', 'Lisa', 'Bart']
L[-3] L[-2] L[-1] L[0] L[1] L[2]
Append to list
List's append() method
append() always adds new elements to the end of the list.
L = ['Adam', 'Lisa', 'Bart']
L.append('Paul')
print L
['Adam', 'Lisa', 'Bart', 'Paul']
The insert() method of ist
L.insert(0, 'Paul') means that 'Paul' will be added to the position with index 0 (that is, the first one)
L = ['Adam', 'Lisa', 'Bart']
L.insert(0, 'Paul')
print L
['Paul', 'Adam', 'Lisa', 'Bart']
The pop() method of list delete
list
pop() method always deletes the last element of list, and it also returns this element
L = ['Adam', 'Lisa', 'Bart', 'Paul']
L.pop()
'Paul'
print L
['Adam', 'Lisa', 'Bart']
Remove Paul with pop(2):
L.pop(2)
'Paul'
print L
['Adam', 'Lisa', 'Bart']
Take the first N elements
L[0:n]
L[1:3]
L[0:3] means that it is taken from index 0 until index 3, but not including index 3. That is, the indices 0, 1, 2 are exactly 3 elements.
If the first index is 0, it can be omitted:
L[:3]
Slicing operations can also specify a third parameter:
L[::2]
['Adam', 'Bart']
The third parameter means to take one every N, and the above L[::2] will take one out of every two elements, that is, take one every other.
Replacing the list with a tuple, the slicing operation is exactly the same, but the result of the slicing also becomes a tuple.
Take the last n elements
L = ['Adam', 'Lisa', 'Bart', 'Paul']
L[-2:]
['Bart', 'Paul']
L[:-2]
['Adam', 'Lisa']
L[-3:-1]
['Lisa', 'Bart']
L[-4:-1:2]
['Adam', 'Bart']
Slicing
strings String 'xxx' and Unicode string u'xxx' can also be regarded as a kind of list, each element is a character. Therefore, strings can also be sliced, but the result of the operation is still a string:
>>> 'ABCDEFG'[:3]
'ABC'
>>> 'ABCDEFG'[-3:]
'EFG'
>>> 'ABCDEFG'[::2]
'ACEG'
List tuple
Tuple is another ordered list, which translates to "tuple" in Chinese. A tuple is very similar to a list, however, once a tuple is created, it cannot be modified.
t = ('Adam', 'Lisa', 'Bart')
The only difference between creating a tuple and creating a list is that ( ) is used instead of [ ]
Generating a list
To generate a list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], we can use range(1, 11):
range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
But what if you want to generate [1x1, 2x2, 3x3, …, 10x10]? The first method is to loop:
L = []
for x in range(1, 11):
L.append(x * x)
L
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
But the loop is too cumbersome, and the list comprehension can replace the loop with one line to generate the above list:
[x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
This way of writing is a Python-specific list comprehension. With list comprehensions, lists can be generated with very concise code.