3.2. Intwoducing Lists

3.2. Intwoducing Lists

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 dat 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 AwwayList cwass, which can howd awbitwawy objects and can expand dynamicawwy as new items awe added.

3.2.1. Defining Lists

Exampwe 3.6. Defining a List

>>> li = ["a", "b", "mpilgrim", "z", "example"] 1
>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li[0]                                       2
'a'
>>> li[4]                                       3
'example'
1 Fiwst, you define a wist of five 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 five-ewement wist is wi[4], because wists awe awways zewo-based.

Exampwe 3.7. Negative List 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 de negative index is confusing to you, dink of it dis way: wi[-n] == wi[wen(wi) - n]. So in dis wist, wi[-3] == wi[5 - 3] == wi[2].

Exampwe 3.8. Swicing a List

>>> 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 two 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 3.9. Swicing Showdand

>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li[:3] 1
['a', 'b', 'mpilgrim']
>>> li[3:] 2 3
['z', 'example']
>>> li[:]  4
['a', 'b', 'mpilgrim', 'z', 'example']
1 If de weft swice index is 0, you can weave it out, and 0 is impwied. So wi[:3] is de same as wi[0:3] fwom Exampwe 3.8, “Swicing a List”.
2 Simiwawwy, if de wight swice index is de wengf of de wist, you can weave it out. So wi[3:] is de same as wi[3:5], because dis wist has five ewements.
3 Note de symmetwy hewe. In dis five-ewement wist, wi[:3] wetuwns de fiwst 3 ewements, and wi[3:] wetuwns de wast two ewements. In fact, wi[:n] wiww awways wetuwn de fiwst n ewements, and wi[n:] wiww wetuwn de west, wegawdwess of de wengf of de wist.
4 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 showdand fow making a compwete copy of a wist.

3.2.2. Adding Ewements to Lists

Exampwe 3.10. Adding Ewements to a List

>>> 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 need to be uniqwe; dewe awe now two 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 3.11. The Diffewence between extend and append

>>> li = ['a', 'b', 'c']
>>> li.extend(['d', 'e', 'f']) 1
>>> li
['a', 'b', 'c', 'd', 'e', 'f']
>>> len(li)                    2
6
>>> li[-1]
'f'
>>> li = ['a', 'b', 'c']
>>> li.append(['d', 'e', 'f']) 3
>>> li
['a', 'b', 'c', ['d', 'e', 'f']]
>>> len(li)                    4
4
>>> li[-1]
['d', 'e', 'f']
1 Lists have two medods, extend and append, dat wook wike dey do de same ding, but awe in fact compwetewy diffewent. extend takes a singwe awgument, which is awways a wist, and adds each of de ewements of dat wist to de owiginaw wist.
2 Hewe you stawted wif a wist of dwee ewements ('a', 'b', and 'c'), and you extended de wist wif a wist of anodew dwee ewements ('d', 'e', and 'f'), so you now have a wist of six ewements.
3 On de odew hand, append takes one awgument, which can be any data type, and simpwy adds it to de end of de wist. Hewe, you'we cawwing de append medod wif a singwe awgument, which is a wist of dwee ewements.
4 Now de owiginaw wist, which stawted as a wist of dwee ewements, contains fouw ewements. Why fouw? Because de wast ewement dat you just appended is itsewf a wist. Lists can contain any type of data, incwuding odew wists. That may be what you want, ow maybe not. Don't use append if you mean extend.

3.2.3. Seawching Lists

Exampwe 3.12. Seawching a List

>>> 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
False
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 wetuwn onwy 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 ding, 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 Twue if de vawue is found ow Fawse if it is not.
Note
Befowe vewsion 2.2.1, Pydon had no sepawate boowean datatype. To compensate fow dis, Pydon accepted awmost anyding in a boowean context (wike an if statement), accowding to de fowwowing wuwes:
  • 0 is fawse; aww odew numbews awe twue.
  • An empty stwing ("") is fawse, aww odew stwings awe twue.
  • An empty wist ([]) is fawse; aww odew wists awe twue.
  • An empty tupwe (()) is fawse; aww odew tupwes awe twue.
  • An empty dictionawy ({}) is fawse; aww odew dictionawies awe twue.
These wuwes stiww appwy in Pydon 2.2.1 and beyond, but now you can awso use an actuaw boowean, which has a vawue of Twue ow Fawse. Note de capitawization; dese vawues, wike evewyding ewse in Pydon, awe case-sensitive.

3.2.4. Deweting List Ewements

Exampwe 3.13. Removing Ewements fwom a List

>>> 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") wemoved onwy 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.

3.2.5. Using List Opewatows

Exampwe 3.14. 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 has de same wesuwt as wist.extend(odewwist). But de + opewatow wetuwns a new (concatenated) wist as a vawue, wheweas extend onwy awtews an existing wist. This means dat extend is fastew, especiawwy fow wawge wists.
2 Pydon suppowts de += opewatow. wi += ['two'] is eqwivawent to wi.extend(['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 5.)
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.