Lists

  • List consist of a sequnece of different types delimited by square barckets [ and ]

  • Unlike strings which only contain characters, list elements can be anything, including other lists

In [1]: alist=['The','principal','author','of','Python','is',['Guido','van','Rossum']]

In [2]: alist[6]
Out[2]: ['Guido', 'van', 'Rossum']

In [3]: alist[6][0]
Out[3]: 'Guido'
  • lists are mutable and strings are immutable

In [4]: alist[1]='first'

In [5]: alist
Out[5]: ['The', 'first', 'author', 'of', 'Python', 'is', ['Guido', 'van', 'Rossum']]

In [6]: astring="Van Rossum is a big fan of Monty Python's Flying Circus"

In [7]: astring[1]='x'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/net/rowley/ifs/data/bcc/duan/test_python/<ipython-input-7-7abb36ddd2dd> in <module>()
----> 1 astring[1]='x'

TypeError: 'str' object does not support item assignment
  • We can grow lists in several ways - using insert, append and list concatenation

In [8]: blist=['Python','was','conceived','in','1989']

In [9]: blist
Out[9]: ['Python', 'was', 'conceived', 'in', '1989']

In [10]: blist.append('around Christmas')

In [11]: blist
Out[11]: ['Python', 'was', 'conceived', 'in', '1989', 'around Christmas']

In [12]: blist=blist+["as","a","hobby","project"]

In [13]: blist
Out[13]: 
['Python',
 'was',
 'conceived',
 'in',
 '1989',
 'around Christmas',
 'as',
 'a',
 'hobby',
 'project']

In [14]: blist[4:4]=["December",]

In [15]: blist
Out[15]: 
['Python',
 'was',
 'conceived',
 'in',
 'December',
 '1989',
 'around Christmas',
 'as',
 'a',
 'hobby',
 'project']
  • We can remove items from a list by using pop, del or assigning a slice to the empty list

In [16]: blist.pop()
Out[16]: 'project'
In [17]: blist
Out[17]: 
['Python',
 'was',
 'conceived',
 'in',
 'December',
 '1989',
 'around Christmas',
 'as',
 'a',
 'hobby']

In [18]: del blist[4]

In [19]: blist
Out[19]: 
['Python',
 'was',
 'conceived',
 'in',
 '1989',
 'around Christmas',
 'as',
 'a',
 'hobby']

In [20]: del blist[6:9]

In [21]: blist
Out[21]: ['Python', 'was', 'conceived', 'in', '1989', 'around Christmas']

In [22]: blist[3:5]=[]

In [22]: blist
Out[22]: ['Python', 'was', 'conceived', 'around Christmas']

Last updated

Massachusetts Institute of Technology