Basic List Operations

Because they are sequences, lists support many of the same operations as strings. For example, lists respond to the + and * operators much like strings—they mean concatenation and repetition here too, except that the result is a new list, not a string:

% python
>>> len([1, 2, 3])                           # Length
3
>>> [1, 2, 3] + [4, 5, 6]                    # Concatenation
[1, 2, 3, 4, 5, 6]
>>> ['Ni!'] * 4                              # Repetition
['Ni!', 'Ni!', 'Ni!', 'Ni!']

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

Although the + operator works the same for lists and strings, it’s important to know that it expects the same sort of sequence on both sides—otherwise, you get a type error when the code runs. For instance, you cannot concatenate a list and a string unless you first convert the list to a string (using tools such as str or % formatting) or convert the string to a list (the list built-in function does the trick):

>>> str([1, 2]) + "34"               # Same as "[1, 2]" + "34"
'[1, 2]34'
>>> [1, 2] + list("34")              # Same as [1, 2] + ["3", "4"]
[1, 2, '3', '4']