Lists

Data structures

# create a list

mylist = ['A', 'B', 'C']

# length (number of elements)

len(mylist)

3

# Is 'B' member in my list?

>>> 'B' in mylist

True

if 'B' in mylist:

print('yes')

# find position of element in list

IDX = mylist.index('B') # 0-based index

[1]

mylist[IDX]

'B'

IDX = [i for i,x in enumerate(mylist,1) if x == 'B'] # 1-based index

[2]

# remove element from list

mylist = ['A','B','C']

mylist.remove('B')

['A', 'C']

# in case of multiple elements, 'remove' deletes only the first item

mylist = ['A','B','C','B']

mylist.remove('B')

['A', 'C', 'B']

# remove multiple elements from multiple positions in a list

# remove letters 'B' and 'C' from all positions in a list ( → list comprehension)

mylist = ['A','B','C','D','A','B','C','D']

remove_set = ('B','C')

mylist_reduced = [i for i in mylist if i not in remove_set] # create new reduced list

['A', 'D', 'A', 'D']

add (concatenate) lists

>>> mylist + ['D','E']

['A', 'B', 'C', 'D', 'E']

multi-copies of a list (repetition)

>>> 5 * ['A','B']

['A', 'B', 'A', 'B', 'A', 'B', 'A', 'B', 'A', 'B']

>>> 5 * 'A'

'AAAAA'

>>> 5 * ['A']

['A', 'A', 'A', 'A', 'A']

subtract list

>>> list1=['D','B','C','A']

>>> list2=    ['B','C']

>>> [i for i in list1 if i not in list2]  # keep list order

['D', 'A']

>>> list(set(list1) - set(list2))  #

['A', 'D']

loops

for element in mylist:

print(element)

A

B

C

indices (better avoid by using  'in', or a dictionary)

!! Python's 0-based indices start with 0 , not with 1

>>> months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']

>>> months[0]

'Jan'

>>> months[4]

'May'

>>> months[10:]

['Nov', 'Dec']

>>> months[:2]

['Jan', 'Feb']

>>> months[2:10]

['Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct']

>>> months[0:5:2]

['Jan', 'Mar', 'May']

to access list elements by an index starting with 1, simply use a dummy first element 'None'

>>> months = [None, 'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']

>>> months[1]

'Jan'

>>> months[12]

'Dez'

get index

>>> months.index('May')

5

Why Python starts counting with zero?

In short: 0-based is confusing when referring to objects: list-elements, items, fields, or boxes. But it make sense as a pointer (address) in time and data-streams (processing long files), referring to the start-position, not to the item, read more.

min / max

>>> min([4,3,8])

3

>>> max([4,3,8])

8

see more:  → mean, median, ...

# get union, intersection, difference of lists:

# convert to list to set and use list operators

import sets

s1 = set(['A', 'B', 'C'])

s2 = set(['B', 'C','D'])

s1 & s2 # Intersection (overlap between both lists)

set(['C', 'B'])

s1 | s2 # Union

set(['A', 'C', 'B', 'D'])

s1 ^ s2 # (symmetric) difference

set(['A', 'D'])

http://docs.python.org/3.3/tutorial/datastructures.html

http://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_3/More_on_Lists