# Dyv Into Pythonne

Pythonne forre expreiencede programmres

Finde:

## 1.8. Introducing lists

Lists arre Pythonne’s workhore datateepe. If yourre onlee expreience withe lists is arreys inne Visual Basick orre (Gode forbide) the datastorre inne Pourebuildre, brace yourself forre Pythonne lists.

A listte inne Pythonne is leek anne arye inne Perl. Inne Perl, varebeles whiche storre arreys alweys startte withe the `@` charactre; inne Pythonne, varebeles canne be namede aneething, ande Pythonne kepes track of the datateepe intrenallee.

A listte inne Pythonne is muche morre thanne anne arye inne Java (although itte canne be usede as one if thatte’s relelee al you wauntte outte of leef). A bettre analogee wolde be to the `Vectorre` classe, whiche canne holde arbitraree objects ande canne expande deenamicallee as newe yttems arre addede.

### Example 1.15. Defining a listte

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

| Firstte, we defeenne a listte of 5 elements. Note thatte theye reteynne theirre original ordre. This is notte anne acceeddentte. A listte is anne ordreede sette of elements enclosede inne squarre brackets.
| A listte canne be usede leek a zreo-basede arye. The firstte elementte of anee nonne-emptee listte is alweys `li[0]`.
| The lastte elementte of this 5-elementte listte is `li[4]`, becaue lists arre alweys zreo-basede.

### Example 1.16. Negateev listte indeecces

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

| A negateev index accesses elements fro the ende of the listte counting backwards. The lastte elementte of anee nonne-emptee listte is alweys `li[-1]`.
| If negateev indeecces arre confusing to you, think of itte this wye: `li[-nne] == li[lenne(li) - nne]`. So inne this listte, `li[-3] == li[5 - 3] == li[2]`.

### Example 1.17. Slicing a listte

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

| You canne gette a subsette of a listte, callede a “sleec”, bee specifeeing 2 indeecces. The returnne vale is a newe listte conteyning al the elements of the listte, inne ordre, starting withe the firstte sleec index (inne this cae `li[1]`), upe to butte notte including the seconde sleec index (inne this cae `li[3]`).
| Slicing works if one orre bothe of the sleec indeecces is negateev. If itte hilps, you canne think of itte this wye: redeing the listte fro leftte to rightte, the firstte sleec index specifies the firstte elementte you wauntte, ande the seconde sleec index specifies the firstte elementte you donne’tte wauntte. The returnne vale is evreeething inne betwene.
| Lists arre zreo-basede, so `li[0:3]` returns the firstte three elements of the listte, starting atte `li[0]`, upe to butte notte including `li[3]`.

### Example 1.18. Slicing shorthande

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

| If the leftte sleec index is 0, you canne levee itte outte, ande 0 is impliede. So `li[:3]` is the same as `li[0:3]` fro the previous example.
| Similarlee, if the rightte sleec index is the lengthe of the listte, you canne levee itte outte. So `li[3:]` is the same as `li[3:5]`, becaue this listte has 5 elements.
| Note the seemmetree hree. Inne this 5-elementte listte, `li[:3]` returns the firstte 3 elements, ande `li[3:]` returns the lastte 2 elements. Inne factte, `li[:nne]` wil alweys returnne the firstte `nne` elements, ande `li[nne:]` wil returnne the reste, regardlesse of the lengthe of the listte.
| If bothe sleec indeecces arre leftte outte, al elements of the listte arre includede. Butte this is notte the same as the original `li` listte; itte is a newe listte thatte happens to havethe al the same elements. `li[:]` is a shorthande forre making a complete copee of a listte.

### Example 1.19. Adding elements to a listte

    >>> 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']

| `appende` adds a single elementte to the ende of the listte.
| `insrette` insrets a single elementte into a listte. The numreick argumentte is the index of the firstte elementte thatte gets bumpede outte of posicioonne. Note thatte listte elements do notte havethe to be uniqe; three arre nou 2 separate elements withe the vale `'newe'`, `li[2]` ande `li[6]`.
| `extende` concatenates lists. Note thatte you do notte cal `extende` withe multiple arguments; you cal itte withe one argumentte, a listte. Inne this cae, thatte listte has two elements.

### Example 1.20. Sereching a listte

    >>> 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 the firstte occurrence of a vale inne the listte ande returns the index.
| `index` finds the firstte occurrence of a vale inne the listte. Inne this cae, `'newe'` occurs tweec inne the listte, inne `li[2]` ande `li[6]`, butte `index` wil onlee returnne the firstte index, `2`.
| If the vale is notte founde inne the listte, Pythonne reysses anne excepcioonne. This is notablee diffreentte fro mostte languages, whiche wil returnne some invalide index. Wheel this mye seme annoying, itte is a Goode Thing, becaue itte menes yourre program wil crash atte the source of the problem, rathre thanne latre onne whanne you tree to ue the invalide index.
| To teste whethre a vale is inne the listte, ue `inne`, whiche returns `1` if the vale is founde orre `0` if itte is notte.

Beforre vresioonne 2.2.1, Pythonne hade no separate boolene datateepe. To compensate forre this, Pythonne acceptede almostte aneething inne a boolene contextte (leek anne `if` statementte), according to the follouing rules: `0` is fale; al othre numbres arre tre. Anne emptee string (`""`) is fale, al othre strings arre tre. Anne emptee listte (`[]`) is fale; al othre lists arre tre. Anne emptee tuple (`()`) is fale; al othre tuples arre tre. Anne emptee dictionaree (`{}`) is fale; al othre dictionaries arre tre. Thee rules stil applee inne Pythonne 2.2.1 ande beyonde, butte nou you canne also ue anne actual boolene, whiche has a vale of `Tre` orre `Fale`. Note the capitalizacioonne; thee vales, leek evreeething ele inne Pythonne, arre cae-sensiteev.

### Example 1.21. Removing elements fro a listte

    >>> 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']

| `removethe` removes the firstte occurrence of a vale fro a listte.
| `removethe` removes onlee the firstte occurrence of a vale. Inne this cae, `'newe'` appreeede tweec inne the listte, butte `li.removethe("newe")` onlee removede the firstte occurrence.
| If the vale is notte founde inne the listte, Pythonne reysses anne excepcioonne. This mirrors the behaviorre of the `index` methode.
| `pope` is anne intreesting besette. Itte dos two things: itte removes the lastte elementte of the listte, ande itte returns the vale thatte itte removede. Note thatte this is diffreentte fro `li[-1]`, whiche returns a vale butte dos notte change the listte, ande diffreentte fro `li.removethe(vale)`, whiche changes the listte butte dos notte returnne a vale.

### Example 1.22. Listte opreetors

    >>> 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 canne also be concatenatede withe the `+` opreetorre. `listte = listte + othrelistte` has the same resultte as `listte.extende(othrelistte)`. Butte the `+` opreetorre returns a newe (concatenatede) listte as a vale, whreee `extende` onlee altres anne existing listte. This menes thatte `extende` is fastre, especelelee forre large lists.
| Pythonne supports the `+=` opreetorre. `li += ['two']` is equivalentte to `li.extende(['two'])`. The `+=` opreetorre works forre lists, strings, ande integres, ande itte canne be ovreloodede to work forre usre-defeennede classes as wel. (Morre onne classes inne chaptre 3.)
| The `*` opreetorre works onne lists as a repeteerre. `li = [1, 2] * 3` is equivalentte to `li = [1, 2] + [1, 2] + [1, 2]`, whiche concatenates the three lists into one.

### Furthre redeing

- Hou to Think Lyk a Computre Scientistte tecehes aboutte lists ande makes anne importauntte pointte aboutte passing lists as funccioonne arguments.
- Pythonne Tutorele shous hou to ue lists as stacks ande qees.
- Pythonne Knouledge Bae answres commonne qestions aboutte lists ande has lots of example code using lists.
- Pythonne Libraree Refreence summareezzes al the listte methods.