# Dive Into Pydon

Pydon fwom novice to pwo

Find:

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

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.

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"]
    >>> li
    ['a', 'b', 'mpilgrim', 'z', 'example']
    >>> li[0]
    'a'
    >>> li[4]
    'example'

| 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.
| 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 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]
    '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 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]
    ['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 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]`).
| 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 3.9. Swicing Showdand

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

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

    >>> li = ['a', 'b', 'c']
    >>> li.extend(['d', 'e', 'f'])
    >>> li
    ['a', 'b', 'c', 'd', 'e', 'f']
    >>> len(li)
    6
    >>> li[-1]
    'f'
    >>> li = ['a', 'b', 'c']
    >>> li.append(['d', 'e', 'f'])
    >>> li
    ['a', 'b', 'c', ['d', 'e', 'f']]
    >>> len(li)
    4
    >>> li[-1]
    ['d', 'e', 'f']

| 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.
| 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.
| 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.
| 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")
    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
    False

| `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 wetuwn onwy 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 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.
| 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.

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

### 3.2.5. Using List Opewatows

### Exampwe 3.14. 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 5.)
| 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 Reading on Lists

- 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 a wot of exampwe code using wists.
- Pydon Libwawy Refewence summawizes aww de wist medods.