python-variables-collections
python-variables-collections
Felix Biessmann
Lecture 2: Variables, Types, Operators and Data Structures
2 Python Variables
[2]: x = 1 # x is an integer
print(x)
x = 'hello' # now x is a string
print(x)
x = [1, 2, 3] # now x is a list
print(x)
1
hello
[1, 2, 3]
1
2.3 Dynamic Typing: Caveats
x = 2 # x is an integer
print(multiply_by_two(x))
22
[5]: x = 1 # x is an integer
type(x)
[5]: int
[6]: str
[7]: list
2
[8]: x = [1] # x is a list
issubclass(type(x), list)
[8]: True
3.1 Integers
[9]: x = 1
type(x)
[9]: int
[10]: 0.5
3.2 Floats
[11]: x = 1.
type(x)
[11]: float
[12]: float
3
[13]: # equality checks between floats and ints actually work
x == 1
[13]: True
e or E can be read “…times ten to the…”, so that 1.4e6 is interpreted as 1.4 × 106
[14]: x = 1400000.00
y = 1.4e6
print(x == y)
True
abc
[15]: NoneType
[16]: True
[17]: type(result)
[17]: bool
4
3.4.1 Many types are implicitly cast to booleans:
3.4.2 Numbers
[18]: bool(2014)
[18]: True
[19]: bool(0)
[19]: False
[20]: bool(None)
[20]: False
3.4.4 Strings
[21]: bool("")
[21]: False
[22]: bool("abc")
[22]: True
3.4.5 Lists
[23]: True
[24]: bool([])
[24]: False
5
3.5 Python variables are pointers
[25]: x = [1, 2, 3]
y = x
print(x)
print(y)
[1, 2, 3]
[1, 2, 3]
[1, 2, 3, 4]
[27]: # however:
x = "Something entirely different"
print(y)
[1, 2, 3, 4]
4 Operators
• Arithmetic Operators
• Bitwise Operators
• Assignment Operators
• Comparison Operators
• Boolean Operators
• Membership Operators
6
Operator Name Description
a * b Multiplication Product of a and b
a / b True division Quotient of a and b
a // b Floor division Quotient of a and b, removing fractional parts
a % b Modulus Integer remainder after division of a by b
a ** b Exponentiation a raised to the power of b
-a Negation The negative of a
+a Unary plus a unchanged (rarely used)
[28]: a = 1
b = 1
a + b
[28]: 2
[29]: a = True
b = False
a & b
[29]: False
a += b a -= b a *= b
a //= b a %= b a **= b
a |= b a ^= b a <<= b
7
[30]: a = 2
a += 2 # equivalent to a = a + 2
print(a)
Operator Description
a and b True if a and b
a or b True if a or b is true
not a True if a is false.
[31]: False
[33]: [False, 2]
[34]: # 25 is odd
25 % 2 == 1
[34]: True
[35]: True
8
[36]: False
[37]: # but
a = [1,2]
b = a
a == b
[37]: True
Operator Description
a is b True if a and b are identical objects
a is not b True if a and b are not identical objects
a in b True if a is a member of b
a not in b True if a is not a member of b
[38]: 1 in [1,2,3]
[38]: True
4.7 Strings
[40]: 2
9
[42]: # concatenation
message + answer
[43]: # multiplication
answer * 3
[43]: '424242'
[44]: 'T'
[47]: 16
[48]: line.find('bear')
[48]: -1
[50]: ['the', 'quick', 'brown', 'fox', 'jumped', 'over', 'a', 'lazy', 'dog']
10
[51]: # joining them back together
'--'.join(line.split())
[51]: 'the--quick--brown--fox--jumped--over--a--lazy--dog'
[52]: x = 3.14159
"This is a bad approximation of pi: " + str(x)
[54]: y = 3
"This is a bad approximation of pi: {} but better than {}".format(x, y)
[54]: 'This is a bad approximation of pi: 3.14159 but better than 3'
[55]: "This is a bad approximation of pi: {1} but better than {0}".format(y, x)
[55]: 'This is a bad approximation of pi: 3.14159 but better than 3'
[56]: 'This is a bad approximation of pi: 3.14159 but \n better than 3'
[58]: width = 5
precision = 3
f'Bad approximation, nice f-string interpolation formatting: {x:{width}.
,→{precision}}'
11
4.7.4 Regular Expressions Recap
[59]: import re
line = 'the quick brown fox jumped over a lazy dog'
regex = re.compile('fox')
match = regex.search(line)
match.start()
[59]: 16
There are many more special regexp characters; for more details, see Python’s regular expression
syntax documentation.
[61]: regex = re.compile(r'\w\s\w')
regex.findall('the fox is 9 years old')
If the special symbols are not enough, you can define your own character sets
[62]: regex = re.compile('[aeiou]')
regex.split('consequential')
12
[64]: regex = re.compile('[A-Z][A-Z][0-9]')
regex.findall('1043879, G2, H6 AH9')
[64]: ['AH9']
4.7.7 Wildcards
[65]: ['AH9']
[66]: ['AH9']
[68]: ['1', '0', '4', '3', '8', '7', '9', 'G2', 'H6', 'AH9']
13
4.7.8 Example: Matching E-Mail Adresses
[70]: email.findall('barack.obama@whitehouse.gov')
[70]: ['obama@whitehouse.gov']
[71]: ['barack.obama@whitehouse.gov']
5 Data Structures
14
Type Name Example Description
dict {'a':1, 'b':2, 'c':3} Unordered (key,value) mapping
set {1, 2, 3} Unordered collection of unique values
5.2 Lists
• Ordered, indexable
• zero-based indexing
• Mutable
• Defined by [1, 2, 3]
[75]: 2
[76]: L[1]
[76]: 3
[77]: L[-1]
[77]: 11
[78]: L[-2]
[78]: 7
[79]: L[0:3]
[79]: [2, 3, 5]
[80]: L[:3]
[80]: [2, 3, 5]
[81]: L[-3:]
15
[82]: L[-3:-1]
[82]: [5, 7]
[84]: [11, 7, 5, 3, 2]
5.2.3 List Indexing and Slicing for Accessing and Assigning Elements
5.3 Lists
Source
5.4 Tuples
• Similar to lists
16
• Immutable
• Defined by (1, 2, 3) or 1, 2, 3
[87]: t = (1, 2, 3)
t
[87]: (1, 2, 3)
[88]: t = 1, 2, 3
t
[88]: (1, 2, 3)
[89]: len(t)
[89]: 3
t[0] = 5
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-86-6dd06f73cec4> in <module>()
----> 1 t[0] = 5
[90]: x = 0.125
x.as_integer_ratio()
[90]: (1, 8)
[91]: 0.125
5.5 Sets
17
[92]: primes = {2, 3, 5, 7}
odds = {1, 3, 5, 7, 9}
5.5.1 Union
[93]: {1, 2, 3, 5, 7, 9}
5.5.2 Intersection
[94]: {3, 5, 7}
5.5.3 Difference
[95]: {2}
18
[96]: {1, 2, 9}
5.6 Dictionaries
• Hash table
• Extremely flexible and versatile
• Fast access
• Unordered
• Defined by key:value pairs within curly braces: {'a':1, 'b':2, 'c':3}
[97]: numbers = {'one':1, 'two':2, 'three':3}
[98]: 2
5.7 Dictionary
Source
19