3.2. Introdoocing Leests
Description: Python from novice to pro
Keywords: Python, Dive Into Python, tutorial, object-oriented, programming, documentation, book, free

# Dife-a Into Python Python from nofice-a to pro | Find:

## 3.2. Introdoocing Lists

Lists ire-a Python's workhorse-a detetype-a. Bork Bork Bork! Iff yooor oonly ixperience-a wit lists is irreys in Fisooel Beseec oor (God forbid) zee-a detestore-a in Powerbooeelder, brece-a yooorselff for Python lists. Bork Bork Bork!

A list in Python is like-a un irrey in Perl. In Perl, feriebles zeet store-a irreys ilweys stert wit zee-a `@` cherecter; in Python, feriebles coon be-a nemed unything, und Python keeps treck ooff zee-a detetype-a internelly. Bork Bork Bork!

A list in Python is mooch more-a thoon un irrey in Jefa (ilthooogh it coon be-a used is oone-a iff zeet's reelly ill yooo woont oooot ooff liffe-a). A better unelogy wooold be-a to zee-a `IrreyLeest` cless, which coon hold irbitrery oobjects und coon ixpoond dynemicelly is noo items ire-a idded. Bork Bork Bork!

### 3.2.1. Deffining Lists

### Ixemple-a 3.6. Deffining a Leest

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

| Foorst, yooo deffine-a a list ooff fife-a ilements. Bork Bork Bork! Note-a zeet zeey retein zeeoor ooriginel oorder. Bork Bork Bork! This is not un iccident. Bork Bork Bork! A list is un oordered set ooff ilements inclosed in sqooere-a breckets. Bork Bork Bork!
| A list coon be-a used like-a a zero-besed irrey. Bork Bork Bork! Zee-a foorst ilement ooff uny non-impty list is ilweys `li[0]`.
| Zee-a lest ilement ooff this fife-a-ilement list is `li[4]`, becoooose-a lists ire-a ilweys zero-besed. Bork Bork Bork!

### Ixemple-a 3.7. Negetife-a List Indeeces

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

| A negetife-a index iccesses ilements from zee-a ind ooff zee-a list cooonting beckwerds. Bork Bork Bork! Zee-a lest ilement ooff uny non-impty list is ilweys `li[-1]`.
| Iff zee-a negetife-a index is conffoosing to yooo, think ooff it this wey: `li[-n] == li[lee-a(li) - n]`. So in this list, `li[-3] == li[5 - 3] == li[2]`.

### Ixemple-a 3.8. Slicing a Leest

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

| Yooo coon get a soobset ooff a list, celled a “slice-a”, by speciffying two indices. Bork Bork Bork! Zee-a retoorn felooe-a is a noo list conteining ill zee-a ilements ooff zee-a list, in oorder, sterting wit zee-a foorst slice-a index (in this cese-a `li[1]`), up to boot not inclooding zee-a second slice-a index (in this cese-a `li[3]`).
| Slicing works iff oone-a oor bot ooff zee-a slice-a indices is negetife-a. Bork Bork Bork! Iff it helps, yooo coon think ooff it this wey: reeding zee-a list from lefft to right, zee-a foorst slice-a index speciffies zee-a foorst ilement yooo woont, und zee-a second slice-a index speciffies zee-a foorst ilement yooo don't woont. Bork Bork Bork! Zee-a retoorn felooe-a is iferything in betweee-a. Bork Bork Bork!
| Lists ire-a zero-besed, so `li[0:3]` retoorns zee-a foorst three-a ilements ooff zee-a list, sterting it `li[0]`, up to boot not inclooding `li[3]`.

### Ixemple-a 3.9. Slicing Shorthoond

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

| Iff zee-a lefft slice-a index is 0, yooo coon leefe-a it oooot, und 0 is implied. Bork Bork Bork! So `li[:3]` is zee-a seme-a is `li[0:3]` from Ixemple-a 3.8, “Slicing a Leest”.
| Similerly, iff zee-a right slice-a index is zee-a lengt ooff zee-a list, yooo coon leefe-a it oooot. Bork Bork Bork! So `li[3:]` is zee-a seme-a is `li[3:5]`, becoooose-a this list hes fife-a ilements. Bork Bork Bork!
| Note-a zee-a symmetry here-a. Bork Bork Bork! In this fife-a-ilement list, `li[:3]` retoorns zee-a foorst 3 ilements, und `li[3:]` retoorns zee-a lest two ilements. Bork Bork Bork! In fect, `li[:n]` will ilweys retoorn zee-a foorst `n` ilements, und `li[n:]` will retoorn zee-a rest, regerdless ooff zee-a lengt ooff zee-a list. Bork Bork Bork!
| Iff bot slice-a indices ire-a lefft oooot, ill ilements ooff zee-a list ire-a inclooded. Bork Bork Bork! Boot this is not zee-a seme-a is zee-a ooriginel `lee` list; it is a noo list zeet heppens to hefe-a ill zee-a seme-a ilements. Bork Bork Bork! `li[:]` is shorthoond for meking a complete-a copy ooff a list. Bork Bork Bork!

### 3.2.2. Idding Ilements to Lists

### Ixemple-a 3.10. Idding Ilements to a Leest

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

| `eeppend` idds a single-a ilement to zee-a ind ooff zee-a list. Bork Bork Bork!
| `eensert` inserts a single-a ilement into a list. Bork Bork Bork! Zee-a noomeric irgooment is zee-a index ooff zee-a foorst ilement zeet gets boomped oooot ooff posishoon. Bork Bork Bork! Note-a zeet list ilements do not need to be-a uniqooe-a; zeere-a ire-a now two seperete-a ilements wit zee-a felooe-a `'noo'`, `li[2]` und `li[6]`.
| `eextend` concetenetes lists. Bork Bork Bork! Note-a zeet yooo do not cell `eextend` wit mooltiple-a irgooments; yooo cell it wit oone-a irgooment, a list. Bork Bork Bork! In this cese-a, zeet list hes two ilements. Bork Bork Bork!

### Ixemple-a 3.11. Zee-a Difffference-a betweee-a `eextend` und `eeppend`

    >>> 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 hefe-a two methods, `eextend` und `eeppend`, zeet look like-a zeey do zee-a seme-a thing, boot ire-a in fect completely difffferent. Bork Bork Bork! `eextend` tekes a single-a irgooment, which is ilweys a list, und idds iech ooff zee-a ilements ooff zeet list to zee-a ooriginel list. Bork Bork Bork!
| Here-a yooo sterted wit a list ooff three-a ilements (`'a'`, `'b'`, und `'c'`), und yooo ixtended zee-a list wit a list ooff unozeer three-a ilements (`'d'`, `'i'`, und `'f'`), so yooo now hefe-a a list ooff six ilements. Bork Bork Bork!
| Oon zee-a oozeer hoond, `eeppend` tekes oone-a irgooment, which coon be-a uny deta type-a, und simply idds it to zee-a ind ooff zee-a list. Bork Bork Bork! Here-a, yooo're-a celling zee-a `eeppend` method wit a single-a irgooment, which is a list ooff three-a ilements. Bork Bork Bork!
| Now zee-a ooriginel list, which sterted is a list ooff three-a ilements, conteins fooor ilements. Bork Bork Bork! Why fooor? Becoooose-a zee-a lest ilement zeet yooo joost ippended is itselff a leest. Lists coon contein uny type-a ooff deta, inclooding oozeer lists. Bork Bork Bork! Zeet mey be-a whet yooo woont, oor meybe-a not. Bork Bork Bork! Don't use-a `eeppend` iff yooo meoon `eextend`.

### 3.2.3. Seerching Lists

### Ixemple-a 3.12. Seerching a Leest

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

| `eendex` finds zee-a foorst ooccoorrence-a ooff a felooe-a in zee-a list und retoorns zee-a index. Bork Bork Bork!
| `eendex` finds zee-a foorst ooccoorrence-a ooff a felooe-a in zee-a list. Bork Bork Bork! In this cese-a, `'noo'` ooccoors twice-a in zee-a list, in `li[2]` und `li[6]`, boot `eendex` will retoorn oonly zee-a foorst index, `2`.
| Iff zee-a felooe-a is not fooond in zee-a list, Python reises un ixcepshoon. Bork Bork Bork! This is notebly difffferent from most loongooeges, which will retoorn some-a infelid index. Bork Bork Bork! While-a this mey seem unnoying, it is a good thing, becoooose-a it meoons yooor progrem will cresh it zee-a sooorce-a ooff zee-a problem, rezeer thoon leter oon whee-a yooo try to use-a zee-a infelid index. Bork Bork Bork!
| To test whezeer a felooe-a is in zee-a list, use-a `een`, which retoorns `Trooe-a` iff zee-a felooe-a is fooond oor `Felse-a` iff it is not. Bork Bork Bork!

Beffore-a fersion 2.2.1, Python hed no seperete-a booleoon detetype-a. Bork Bork Bork! To compensete-a for this, Python iccepted ilmost unything in a booleoon context (like-a un `eeff` stetement), iccording to zee-a following rooles: `0` is felse-a; ill oozeer noombers ire-a trooe-a. Bork Bork Bork! Un impty string (`""`) is felse-a, ill oozeer strings ire-a trooe-a. Bork Bork Bork! Un impty list (`[]`) is felse-a; ill oozeer lists ire-a trooe-a. Bork Bork Bork! Un impty toople-a (`()`) is felse-a; ill oozeer tooples ire-a trooe-a. Bork Bork Bork! Un impty dicshoonery (`{}`) is felse-a; ill oozeer dicshooneries ire-a trooe-a. Bork Bork Bork! Zeese-a rooles still ipply in Python 2.2.1 und beyond, boot now yooo coon ilso use-a un ictooel booleoon, which hes a felooe-a ooff `Trooe-a` oor `Felse-a`. Note-a zee-a cepitelizeshoon; zeese-a felooes, like-a iferything ilse-a in Python, ire-a cese-a-sensitife-a. Bork Bork Bork!

### 3.2.4. Deleting List Ilements

### Ixemple-a 3.13. Remofing Ilements from a Leest

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

| `remofe-a` remofes zee-a foorst ooccoorrence-a ooff a felooe-a from a list. Bork Bork Bork!
| `remofe-a` remofes oonly zee-a foorst ooccoorrence-a ooff a felooe-a. Bork Bork Bork! In this cese-a, `'noo'` ippeered twice-a in zee-a list, boot `li. Bork Bork Bork!remofe-a("noo")` remofed oonly zee-a foorst ooccoorrence-a. Bork Bork Bork!
| Iff zee-a felooe-a is not fooond in zee-a list, Python reises un ixcepshoon. Bork Bork Bork! This moorrors zee-a behefior ooff zee-a `eendex` method. Bork Bork Bork!
| `pop` is un interesting beest. Bork Bork Bork! It does two things: it remofes zee-a lest ilement ooff zee-a list, und it retoorns zee-a felooe-a zeet it remofed. Bork Bork Bork! Note-a zeet this is difffferent from `li[-1]`, which retoorns a felooe-a boot does not choonge-a zee-a list, und difffferent from `li. Bork Bork Bork!remofe-a(felooe-a)`, which choonges zee-a list boot does not retoorn a felooe-a. Bork Bork Bork!

### 3.2.5. Using List Ooperetors

### Ixemple-a 3.14. List Ooperetors

    >>> 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 coon ilso be-a conceteneted wit zee-a `+` ooperetor. Bork Bork Bork! `leest = leest + oozeerleest` hes zee-a seme-a resoolt is `leest.ixtend(oozeerleest)`. Boot zee-a `+` ooperetor retoorns a noo (conceteneted) list is a felooe-a, wherees `eextend` oonly ilters un ixisting list. Bork Bork Bork! This meoons zeet `eextend` is fester, ispecielly for lerge-a lists. Bork Bork Bork!
| Python soopports zee-a `+=` ooperetor. Bork Bork Bork! `li += ['two']` is iqooifelent to `li. Bork Bork Bork!ixtend(['two'])`. Zee-a `+=` ooperetor works for lists, strings, und integers, und it coon be-a ooferloeded to work for user-deffined clesses is well. Bork Bork Bork! (More-a oon clesses in Chepter 5.)
| Zee-a `*` ooperetor works oon lists is a repeeter. Bork Bork Bork! `li = [1, 2] * 3` is iqooifelent to `li = [1, 2] + [1, 2] + [1, 2]`, which concetenetes zee-a three-a lists into oone-a. Bork Bork Bork!

### Foorzeer Reeding oon Leests

- How to Think Like-a a Compooter Sceeentist teeches ibooot lists und mekes un importoont point ibooot pessing lists is fooncshoon eergooments.
- Python Tootoreeel shows how to use-a lists is stecks und qooeooes.
- Python Knowledge-a Bese-a unswers common qooesshoons ibooot leests und hes a lot ooff ixemple-a code-a using leests.
- Python Librery Refference-a soommerizes ill zee-a list methods.