(see https://docs.python.org/2/tutorial/introduction.html#lists)
Lists are a very common concept in Python. Objects can be lists of the aforementioned data types:
In [1]:
l1 = [1, 2, 3, 4, 5, 6] # list of the same data type
l2 = [1, 2.3, 'a'] # list of different data types
l3 = [[1, 2, 3], [4, 5, 6]] # a nested (multidimensional) list
l4 = range(3,10) # a neat way to generate a list of integers
Simple list operations:
In [2]:
print len(l1) # number of items in the list
print l1[0] # access individual items in the list (square brackets!)
l1[0] = 99 # assign a new value to an item
print l1[0] # the value has changed
print l1+[6, 7] # concatenate lists
l1.append(11) # append an item to a list
print len(l1) # the list is longer now
Slicing allows to address certain parts of lists.
Important: Python list indices always start at 0 (zero).
In [3]:
print l1[:] # the whole list
print l1[0:3] # the first 3 items, indices: 0, 1, 2; but not 3
print l1[6:8] # 2 items, indices: 6, 7
print l1[-1] # the last item
print l1[-2] # the second to last item
print l1[::2] # every second item from the whole list
print l1[::-1] # reverse list
More advanced list operations:
In [4]:
print len(l1)
print l1.pop(0) # remove item from list and return its value
print len(l1)
print l1
l1.insert(4,20) # insert element (here: 20) before index (here: 4)
print l1
print min(l1) # minimum value
print max(l1) # maximum value
print sorted(l1, reverse=True) # sort list (in descending order)
print map(lambda x: x*x, l1) # map list on a lambda function (more on lambda function later)
print filter(lambda x: x < 5, l1) # filter list using lambda function
side note: Tuples are similar to lists, but are immutable. Tuples use parantheses instead of square brackets and are often used for function output.
In [5]:
t = (1, 2)
#t[0] = 3 # results in a TypeError
more side notes: string are lists, too.
In [6]:
s = 'abcdefghijklmnopqrstuvwxyz'
print len(s)
print s[10:]
(see https://docs.python.org/2/tutorial/datastructures.html?highlight=dictionary#dictionaries)
Dictionaries can be used for look-up tables. They are useful to make associations between different variables.
In [7]:
weather = {'winter': 'cold', 'spring': 'windy', 'summer':'warm', 'fall': 'cold again'} # mind the curly brackets
season = 'winter'
print season, 'in Flagstaff is', weather[season]
Each element of a dictionary consists of a key and a value ('winter' is a key, 'cold' is the corresponding value). Lists of keys and values can be obtained as:
In [8]:
print weather.keys() # obtain all keys
print weather.values() # obtain all values
Keys and values don't have to have the same datatype:
In [9]:
wordifier = {1: 'one', 2: 'two', 3: 'three'}
print wordifier[2]
Dictionaries can be extended, but note that every key can only appear once in each dictionary:
In [10]:
weather['Thanksgiving'] = 'nice'
print weather['Thanksgiving']
weather['Thanksgiving'] = 'amazing'
print weather['Thanksgiving']
Dictionaries have a length like lists, but they are not necessarily sorted in any way:
In [11]:
print len(weather)
print weather
(see https://docs.python.org/2/tutorial/datastructures.html?highlight=dictionary#sets)
Sets are dictionaries with keys, only. They are useful to list unique elements. Similar to dictionaries, sets are not sorted.
In [12]:
basket = set(['bread', 'eggs', 'butter', 'milk', 'bread']) # note that sets are generated from lists
print basket
It is possible to check if a certain element exists in a set (note the intuitive syntax).
In [13]:
print 'eggs' in basket
print 'cake' in basket
(see https://docs.python.org/2/tutorial/controlflow.html)
checks if a condition is met (or not)
In [14]:
shoppinglist = set(['bread', 'eggs', 'butter', 'milk', 'bread'])
item = 'milk'
if item in shoppinglist:
print 'buy', item
elif item == 'anchovis':
print 'we will never buy anchovis again!'
else:
print 'we still have', item
Note the indentation: everything inside the if statement must be indented by the same number of blanks.
The general syntax is if <condition>
, where <condition>
has to be either True
or False
. Examples for conditions are:
In [15]:
x = 1
print x < 5
print x > 6
print x is not 2 # another example of Python's intuitive syntax
print x is 2
print x < 5 and x > 2
print (x-3) > 1 or (x/2.) > 0
If statements can be put into single lines:
In [16]:
print 'x greater 5' if x > 5 else 'x <= 5' # print uses either string
In [17]:
for item in ['a', 'b', 'c', 'd']: # take each element from list
print item
In [18]:
for n in range(10): # range generates a list of numbers starting with 0
print n
In [19]:
for idx, item in enumerate(['a', 'b', 'c', 'd']): # obtain list index and item at the same time
print idx, item
In [20]:
for item in ['a', 'b', 'c', 'd']:
if item == 'b':
continue # continue allows to escape current loop item and resume with next one
if item == 'd':
break # break stops the for-loop immediately ('d' gets not printed)
print item
A single-line version of the for loop can be used to generate new lists from already existing lists (this is called list comprehension):
In [21]:
[x**2+3*x+1 for x in range(5)]
Out[21]:
Advice: if you are looping through a list, you shouldn't alter this list within the loop. It will most likely mess up things:
In [22]:
i = 0
while i < 10:
print i
i += 1
This is a good example of how to use a while loop:
In [23]:
i = 0
stop = 7
while True:
print i
i += 1
if i >= stop:
print "I'll stop here"
break # break also works in while-loops