![](https://csdnimg.cn/release/download_crawler_static/10682600/bg5.jpg)
In [23]: xs[2] =
'
foo
'
# Lists can contain elements of different types
print(xs)
[3, 1,
'
foo
'
]
In [24]: xs.append(
'
bar
'
)
# Add a new element to the end of the list
print(xs)
[3, 1,
'
foo
'
,
'
bar
'
]
In [25]: x = xs.pop()
# Remove and return the last element of the list
print(x, xs)
bar [3, 1,
'
foo
'
]
As usual, you can find all the gory details about lists in the documentation.
Slicing In addition to accessing list elements one at a time, Python provides concise syntax to
access sublists; this is known as slicing:
In [28]: nums = [1,2,3,4,5]
# range is a built-in function that creates a list of integers
print(nums)
# Prints "[0, 1, 2, 3, 4]"
print(nums[2:4])
# Get a slice from index 2 to 4 (exclusive); prints "[2, 3]"
print(nums[2:])
# Get a slice from index 2 to the end; prints "[2, 3, 4]"
print(nums[:2])
# Get a slice from the start to index 2 (exclusive); prints "[0, 1]"
print(nums[:])
# Get a slice of the whole list; prints ["0, 1, 2, 3, 4]"
print(nums[:-1])
# Slice indices can be negative; prints ["0, 1, 2, 3]"
nums[2:4] = [8, 9]
# Assign a new sublist to a slice
print(nums)
# Prints "[0, 1, 8, 8, 4]"
[1, 2, 3, 4, 5]
[3, 4]
[3, 4, 5]
[1, 2]
[1, 2, 3, 4, 5]
[1, 2, 3, 4]
[1, 2, 8, 9, 5]
Loops You can loop over the elements of a list like this:
In [29]: animals = [
'
cat
'
,
'
dog
'
,
'
monkey
'
]
for animal in animals:
print(animal)
5