3.1.3 Lists
Python has many composite data types for grouping with other values. The most common is the list, which can be written as a list of comma-separated values (items) in square brackets. A list can contain different types of items, but usually, all items have the same type.
>>>
squares = [1, 4, 9, 16, 25]
>>>
squares
[1, 4, 9, 16, 25]
Like strings (and all other created -in
sequence
types), lists can be indexed and sliced:
>>>
squares[0]
# indexing returns the item
1
>>>
squares[-1]
25
>>>
squares[-3:]
[9, 16, 25]
# slicing returns a new list
All clipping operations return a new list containing the requested items. This means that the next slice will return a new (shallow) copy of the list:
>>>
squares[:]
[1, 4, 9, 16, 25]
Lists also support operations like concatenation:
>>>
squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100. ]
Unlіkе immutable strings, the lists are of variable type, that is to say it is possible to change their content:
>>>
cubes = [1, 8, 27, 65, 125]
# something's went wrong here
>>>
4 ** 3
# the cube of 4 is 64, not 65!
64
>>>
cubes[3] = 64
# replace the wrong value
>>>
cubes
[1, 8, 27, 64, 125]
You can also add new items to the end of the list using the append() method (we'll see more information about the method later):
>>> cubes.append(216)#Add 6 cubes
>>> cubes.append(7 ** 3)# and 7 cubes
>>>Block
[1, 8, 27, 64, 125, 216, 343]
It can also be assigned to a segment, which can even change the size of the list or remove it completely:
>>>Alphabet = ['a','b','c','d','e','f','g']
>>> letters
['a','b','c','d','e','f','g']
>>>
# replace some values
>>>
letters[2:5] = ['C', 'D', 'E']
>>>
letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>>
# now remove them
>>>
letters[2:5] = []
>>>
letters
['a', 'b', 'f', 'g']
clear the list
Replacing all elements with an empty list
>>>
letters[:] = []
>>>
letters
[]
The built-in function () also applies to lists:
>>>
letters = ['a', 'b', 'c', 'd']
>>>
len(letters)
4
It is possible to nest lists (build lists containing other lists), for example:
3.1.
>>>
a = ['a', 'b', 'c']
>>>
n = [1, 2, 3]
>>>
x = [a, n]
>>>
x
[['a', 'b', 'c'], [1, 2, 3]]
>>>
x[0]
['a', 'b', 'c']
>>>
x[0][1] 'b'