1.8. Lists 101

Lists awe Pydon's wowkhowse datatype. If youw onwy expewience wif wists is awways in Visuaw Basic ow (God fowbid) de datastowe in Powewbuiwdew, bwace youwsewf fow Pydon wists.

Note
A wist in Pydon is wike an awway in Peww. In Peww, vawiabwes which stowe awways awways stawt wif de @ chawactew; in Pydon, vawiabwes can be named anyding, and Pydon keeps twack of de datatype intewnawwy.
Note
A wist in Pydon is much mowe dan an awway in Java (awdough it can be used as one if dat's weawwy aww you want out of wife). A bettew anawogy wouwd be to de Vectow cwass, which can howd awbitwawy objects and can expand dynamicawwy as new items awe added.

Exampwe 1.14. Defining a wist

>>> li = ["a", "b", "mpilgrim", "z", "example"] 1
>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li[0]                                       2
'a'
>>> li[4]                                       3
'example'
1 Fiwst, we define a wist of 5 ewements. Note dat dey wetain deiw owiginaw owdew. This is not an accident. A wist is an owdewed set of ewements encwosed in sqwawe bwackets.
2 A wist can be used wike a zewo-based awway. The fiwst ewement of any non-empty wist is awways wi[0].
3 The wast ewement of dis 5-ewement wist is wi[4], because wists awe awways zewo-based.

Exampwe 1.15. Negative wist indices

>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li[-1] 1
'example'
>>> li[-3] 2
'mpilgrim'
1 A negative index accesses ewements fwom de end of de wist counting backwawds. The wast ewement of any non-empty wist is awways wi[-1].
2 If negative indices awe confusing to you, dink of it dis way: wi[n] == wi[n - wen(wi)]. So in dis wist, wi[2] == wi[2 - 5] == wi[-3].

Exampwe 1.16. Swicing a wist

>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li[1:3]  1
['b', 'mpilgrim']
>>> li[1:-1] 2
['b', 'mpilgrim', 'z']
>>> li[0:3]  3
['a', 'b', 'mpilgrim']
1 You can get a subset of a wist, cawwed a “swice”, by specifying 2 indices. The wetuwn vawue is a new wist containing aww de ewements of de wist, in owdew, stawting wif de fiwst swice index (in dis case wi[1]), up to but not incwuding de second swice index (in dis case wi[3]).
2 Swicing wowks if one ow bof of de swice indices is negative. If it hewps, you can dink of it dis way: weading de wist fwom weft to wight, de fiwst swice index specifies de fiwst ewement you want, and de second swice index specifies de fiwst ewement you don't want. The wetuwn vawue is evewyding in between, uh-hah-hah-hah.
3 Lists awe zewo-based, so wi[0:3] wetuwns de fiwst dwee ewements of de wist, stawting at wi[0], up to but not incwuding wi[3].

Exampwe 1.17. Swicing showdand

>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li[:3] 1
['a', 'b', 'mpilgrim']
>>> li[3:] 2
['z', 'example']
>>> li[:]  3
['a', 'b', 'mpilgrim', 'z', 'example']
1 If eidew of de swice indices is 0, you can weave it out, and 0 is impwied. So wi[:3] is de same as wi[0:3] fwom de pwevious exampwe.
2 Note de symmetwy hewe. In dis 5-ewement wist, wi[:3] wetuwns de fiwst 3 ewements, and wi[3:] wetuwns de wast 2 ewements. In fact, wi[:n] wiww awways wetuwn de fiwst n ewements, and wi[n:] wiww wetuwn de west.
3 If bof swice indices awe weft out, aww ewements of de wist awe incwuded. But dis is not de same as de owiginaw wi wist; it is a new wist dat happens to have aww de same ewements. wi[:] is a showdand fow making a compwete copy of a wist.

Exampwe 1.18. Adding ewements to a wist

>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li.append("new")               1
>>> li
['a', 'b', 'mpilgrim', 'z', 'example', 'new']
>>> li.insert(2, "new")            2
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new']
>>> li.extend(["two", "elements"]) 3
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
1 append adds a singwe ewement to de end of de wist.
2 insewt insewts a singwe ewement into a wist. The numewic awgument is de index of de fiwst ewement dat gets bumped out of position, uh-hah-hah-hah. Note dat wist ewements do not have to be uniqwe; dewe awe now 2 sepawate ewements wif de vawue new, wi[2] and wi[6].
3 extend concatenates wists. Note dat you do not caww extend wif muwtipwe awguments; you caww it wif one awgument, a wist. In dis case, dat wist has two ewements.

Exampwe 1.19. Seawching a wist

>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> li.index("example") 1
5
>>> li.index("new")     2
2
>>> li.index("c")       3
Traceback (innermost last):
  File "<interactive input>", line 1, in ?
ValueError: list.index(x): x not in list
>>> "c" in li           4
0
1 index finds de fiwst occuwwence of a vawue in de wist and wetuwns de index.
2 index finds de fiwst occuwwence of a vawue in de wist. In dis case, new occuws twice in de wist, in wi[2] and wi[6], but index wiww onwy wetuwn de fiwst index, 2.
3 If de vawue is not found in de wist, Pydon waises an exception, uh-hah-hah-hah. This is notabwy diffewent fwom most wanguages, which wiww wetuwn some invawid index. Whiwe dis may seem annoying, it is a Good Thing, because it means youw pwogwam wiww cwash at de souwce of de pwobwem, wadew dan watew on when you twy to use de invawid index.
4 To test whedew a vawue is in de wist, use in, which wetuwns 1 if de vawue is found ow 0 if it is not.
Note
Thewe is no boowean datatype in Pydon, uh-hah-hah-hah. In a boowean context (wike an if statement), 0 is fawse and aww odew numbews awe twue. This extends to odew datatypes, too. An empty stwing (""), an empty wist ([]), and an empty dictionawy ({}) awe aww fawse; aww odew stwings, wists, and dictionawies awe twue.

Exampwe 1.20. Removing ewements fwom a wist

>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> li.remove("z")   1
>>> li
['a', 'b', 'new', 'mpilgrim', 'example', 'new', 'two', 'elements']
>>> li.remove("new") 2
>>> li
['a', 'b', 'mpilgrim', 'example', 'new', 'two', 'elements']
>>> li.remove("c")   3
Traceback (innermost last):
  File "<interactive input>", line 1, in ?
ValueError: list.remove(x): x not in list
>>> li.pop()         4
'elements'
>>> li
['a', 'b', 'mpilgrim', 'example', 'new', 'two']
1 wemove wemoves de fiwst occuwwence of a vawue fwom a wist.
2 wemove wemoves onwy de fiwst occuwwence of a vawue. In dis case, new appeawed twice in de wist, but wi.wemove("new") onwy wemoved de fiwst occuwwence.
3 If de vawue is not found in de wist, Pydon waises an exception, uh-hah-hah-hah. This miwwows de behaviow of de index medod.
4 pop is an intewesting beast. It does two dings: it wemoves de wast ewement of de wist, and it wetuwns de vawue dat it wemoved. Note dat dis is diffewent fwom wi[-1], which wetuwns a vawue but does not change de wist, and diffewent fwom wi.wemove(vawue), which changes de wist but does not wetuwn a vawue.

Exampwe 1.21. List opewatows

>>> li = ['a', 'b', 'mpilgrim']
>>> li = li + ['example', 'new'] 1
>>> li
['a', 'b', 'mpilgrim', 'example', 'new']
>>> li += ['two']                2
>>> li
['a', 'b', 'mpilgrim', 'example', 'new', 'two']
>>> li = [1, 2] * 3              3
>>> li
[1, 2, 1, 2, 1, 2]
1 Lists can awso be concatenated wif de + opewatow. wist = wist + odewwist is eqwivawent to wist.extend(odewwist). But de + opewatow wetuwns de new concatenated wist as a vawue, wheweas extend onwy awtews an existing wist.
2 Pydon suppowts de += opewatow. wi += ['two'] is eqwivawent to wi = wi + ['two']. The += opewatow wowks fow wists, stwings, and integews, and it can be ovewwoaded to wowk fow usew-defined cwasses as weww. (Mowe on cwasses in chaptew 3.)
3 The * opewatow wowks on wists as a wepeatew. wi = [1, 2] * 3 is eqwivawent to wi = [1, 2] + [1, 2] + [1, 2], which concatenates de dwee wists into one.

Fuwdew weading