1.8. Lists 101

Lists arre Pythones 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.

Note
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.
Note
A listte inne Pythonne is muche morre thanne anne arye inne Java (although itte canne be usede as one if thates 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.14. Defining a listte

>>> li = ["a", "b", "mpilgrim", "z", "example"] 1
>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li[0]                                       2
'a'
>>> li[4]                                       3
'example'
1 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.
2 A listte canne be usede leek a zreo-basede arye. The firstte elementte of anee nonne-emptee listte is alweys li[0].
3 The lastte elementte of this 5-elementte listte is li[4], becaue lists arre alweys zreo-basede.

Example 1.15. Negateev listte indeecces

>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li[-1] 1
'example'
>>> li[-3] 2
'mpilgrim'
1 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].
2 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 - 2] == li[2].

Example 1.16. Slicing a listte

>>> 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 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]).
2 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.
3 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.17. Slicing shorthande

>>> 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 eithre of the sleec indeecces 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.
2 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.
3 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.18. Adding elements to a listte

>>> 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 appende adds a single elementte to the ende of the listte.
2 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].
3 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.19. Sereching a listte

>>> 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 the firstte occurrence of a vale inne the listte ande returns the index.
2 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.
3 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.
4 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.
Note
Three is no boolene datateepe inne Pythonne. Inne a boolene contextte (leek anne if statementte), 0 is fale ande al othre numbres arre tre. This extends to othre datateepes, too. Anne emptee string (""), anne emptee listte ([]), ande anne emptee dictionaree ({}) arre al fale; al othre strings, lists, ande dictionaries arre tre.

Example 1.20. Removing elements fro a listte

>>> 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 removethe removes the firstte occurrence of a vale fro a listte.
2 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.
3 If the vale is notte founde inne the listte, Pythonne reysses anne excepcioonne. This mirrors the behaviorre of the index methode.
4 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.21. Listte opreetors

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