l = [2, 5, 2, 3, 7]
type(l)
list
Lists can be heterogeneous, but we typically don't use that.
a = 'spezi'
[3, 'abc', 1.3e20, [a, a, 2]]
[3, 'abc', 1.3e+20, ['spezi', 'spezi', 2]]
t = 'white', 77, 1.5
type(t)
tuple
color, width, scale = t
width
77
'a string can be written in single quotes'
'a string can be written in single quotes'
Strings can also be written with double quotes, or over multiple lines with triple-quotes.
"this makes it easier to use the ' character"
"this makes it easier to use the ' character"
"""This is a multiline string.
You see? I continued after a blank line."""
'This is a multiline string.\n\nYou see? I continued after a blank line.'
'{} times {} equals {:.2f}'.format('pi', 2, 6.283185307179586)
'pi times 2 equals 6.28'
Accessing arguments by position or name is more readable.
'{1} times {0} equals {2:.2f}'.format('pi', 2, 6.283185307179586)
'2 times pi equals 6.28'
'{number} times {amount} equals {result:.2f}'.format(number='pi', amount=2,
result=6.283185307179586)
'pi times 2 equals 6.28'
[1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
'bier' in 'we drinken bier vanaf half 5'
True
'abcdefghijkl'[5]
'f'
'abcdefghijkl'[4:8]
'efgh'
'abcdefghijkl'[:3]
'abc'
We can also define the step k
with s[i:j:k]
.
'abcdefghijkl'[7:3:-1]
'hgfe'
len('attacgataggcatccgt')
18
max([17, 86, 34, 51])
86
('atg', 22, True, 'atg').count('atg')
2
l = [1, 2, 3, 4]
l[3] = 7
l.append(1)
l[1:3] = [3, 2]
l.sort()
l.reverse()
l
[7, 3, 2, 1, 1]
d = {'a': 27, 'b': 18, 'c': 12}
type(d)
dict
d['e'] = 17
'e' in d
True
d.update({'a': 18, 'f': 2})
d
{'a': 18, 'b': 18, 'c': 12, 'e': 17, 'f': 2}
d['b']
18
d.keys()
['a', 'c', 'b', 'e', 'f']
d.values()
[18, 12, 18, 17, 2]
d.items()
[('a', 18), ('c', 12), ('b', 18), ('e', 17), ('f', 2)]
x = {12, 28, 21, 17}
type(x)
set
x.add(12)
x
{12, 17, 21, 28}
x.discard(21)
x
{12, 17, 28}
17 in {12, 28, 21, 17}
True
{12, 28, 21, 17} | {12, 18, 11}
{11, 12, 17, 18, 21, 28}
{12, 28, 21, 17} & {12, 18, 11}
{12}
True or False
True
True and False
False
not False
True
22 * 3 > 66
False
We have two equivalence relations: value equality (==
) and object identity (is
).
a, b = [1, 2, 3], [1, 2, 3]
a == b
True
a is b
False
if 26 <= 17:
print 'Fact: 26 is less than or equal to 17'
elif (26 + 8 > 14) == True:
print 'Did we need the ` == True` part here?'
else:
print 'Nothing seems true'
Did we need the ` == True` part here?
i = 0
while i < 5:
print i
i += 1
0 1 2 3 4
if False:
if False:
print 'Why am I here?'
else:
while True:
print 'When will it stop?'
print "And we're back to the first indentation level"
Some editors can be configured to behave just like that.
# Add 42 to this list.
l.append(42)
pass
statements¶If you ever need a statement syntactically but don't want to do anything, use pass
.
while False:
# This is never executed anyway.
pass
help(range)
Help on built-in function range in module __builtin__: range(...) range([start,] stop[, step]) -> list of integers Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements.
In IPython you can do it faster by typing:
range?
We'll shortly use the following built-in functions.
range(5, 16)
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
zip(['red', 'white', 'blue'], range(3))
[('red', 0), ('white', 1), ('blue', 2)]
list('abcdefghijk')
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
colors = ['red', 'white', 'blue', 'orange']
cities = ['leiden', 'utrecht', 'warmond', 'san francisco']
The for
statement can iterate over sequence items.
for color in colors:
print color
red white blue orange
for character in 'blue':
print character
b l u e
i = 0
while i < len(colors):
print colors[i]
i += 1
red white blue orange
for i in range(len(colors)):
print colors[i]
red white blue orange
We call them unpythonic.
for i, color in enumerate(colors):
print i, '->', color
0 -> red 1 -> white 2 -> blue 3 -> orange
for city, color in zip(cities, colors):
print city, '->', color
leiden -> red utrecht -> white warmond -> blue san francisco -> orange
for key in {'a': 33, 'b': 17, 'c': 18}:
print key
a c b
Iterating over a file yields lines.
for line in open('data/short_file.txt'):
print line
this short file has two lines it is used in the example code
There are many more useful iterables in Python.
First we are going to make a list and fill it with a simple sequence. Then we are going to use this list to print something.
We are going to make a repeating DNA sequence and extract some subsequences from it.
Note: A suffix is an ending. For example, the word "spam" has five suffixes: "spam", "pam", "am", "m" and "".
Hint: All elements in a set are unique.
Calculate all coordinates of the line x=y with x < 100.
Note: This is the sequence (0, 0), (1, 1), ... (99, 99)
We are going to store the output of a function ($f(x) = x^2$) together with its input in a dictionary.
from IPython.display import HTML
def css_styling():
styles = open('styles/custom.css', 'r').read()
return HTML('<style>' + styles + '</style>')
css_styling()