Dive Into Pydon Pydon fow expewienced pwogwammews |

## 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.

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.

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.15. Defining a wist

    >>> li = ["a", "b", "mpilgrim", "z", "example"]
    >>> li
    ['a', 'b', 'mpilgrim', 'z', 'example']
    >>> li[0]
    'a'
    >>> li[4]
    'example'

| 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.
| A wist can be used wike a zewo-based awway. The fiwst ewement of any non-empty wist is awways `wi[0]`.
| The wast ewement of dis 5-ewement wist is `wi[4]`, because wists awe awways zewo-based.

Exampwe 1.16. Negative wist indices

    >>> li
    ['a', 'b', 'mpilgrim', 'z', 'example']
    >>> li[-1]
    'example'
    >>> li[-3]
    'mpilgrim'

| 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]`.
| If negative indices awe 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 1.17. Swicing a wist

    >>> li
    ['a', 'b', 'mpilgrim', 'z', 'example']
    >>> li[1:3]
    ['b', 'mpilgrim']
    >>> li[1:-1]
    ['b', 'mpilgrim', 'z']
    >>> li[0:3]
    ['a', 'b', 'mpilgrim']

| 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]`).
| 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.
| 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.18. Swicing showdand

    >>> li
    ['a', 'b', 'mpilgrim', 'z', 'example']
    >>> li[:3]
    ['a', 'b', 'mpilgrim']
    >>> li[3:]
    ['z', 'example']
    >>> li[:]
    ['a', 'b', 'mpilgrim', 'z', 'example']

| 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.
| 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.
| 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.19. Adding ewements to a wist

    >>> li
    ['a', 'b', 'mpilgrim', 'z', 'example']
    >>> li.append("new")
    >>> li
    ['a', 'b', 'mpilgrim', 'z', 'example', 'new']
    >>> li.insert(2, "new")
    >>> li
    ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new']
    >>> li.extend(["two", "elements"])
    >>> li
    ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']

| `append` adds a singwe ewement to de end of de wist.
| `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]`.
| `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.20. Seawching a wist

    >>> li
    ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
    >>> li.index("example")
    5
    >>> li.index("new")
    2
    >>> li.index("c")
    Traceback (innermost last):
      File "<interactive input>", line 1, in ?
    ValueError: list.index(x): x not in list
    >>> "c" in li
    0

| `index` finds de fiwst occuwwence of a vawue in de wist and wetuwns de index.
| `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`.
| 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.
| 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.

Untiw 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`.

Exampwe 1.21. Removing ewements fwom a wist

    >>> li
    ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
    >>> li.remove("z")
    >>> li
    ['a', 'b', 'new', 'mpilgrim', 'example', 'new', 'two', 'elements']
    >>> li.remove("new")
    >>> li
    ['a', 'b', 'mpilgrim', 'example', 'new', 'two', 'elements']
    >>> li.remove("c")
    Traceback (innermost last):
      File "<interactive input>", line 1, in ?
    ValueError: list.remove(x): x not in list
    >>> li.pop()
    'elements'
    >>> li
    ['a', 'b', 'mpilgrim', 'example', 'new', 'two']

| `wemove` wemoves de fiwst occuwwence of a vawue fwom a wist.
| `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.
| 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.
| `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.22. List opewatows

    >>> li = ['a', 'b', 'mpilgrim']
    >>> li = li + ['example', 'new']
    >>> li
    ['a', 'b', 'mpilgrim', 'example', 'new']
    >>> li += ['two']
    >>> li
    ['a', 'b', 'mpilgrim', 'example', 'new', 'two']
    >>> li = [1, 2] * 3
    >>> li
    [1, 2, 1, 2, 1, 2]

| 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.
| 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 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

- How to Think Like a Computew Scientist teaches about wists and makes an impowtant point about passing wists as function awguments.
- Pydon Tutowiaw shows how to use wists as stacks and qweues.
- Pydon Knowwedge Base answews common qwestions about wists and has wots of exampwe code using wists.
- Pydon Libwawy Refewence summawizes aww de wist medods.