Variable Name
alphabet, number
no reserved-keywords
Primitive data types
Dynamic Typing: declare data type during execution
1
2
3
4
5
6
7
8
9
10
11
12
13
| # int
x1 = 1
# float
x2 = 3.3
# string
x3 = 'abc'
# bool
x4 = True
print(type(x1))
print(type(x2))
print(type(x3))
print(type(x4))
|
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
Data Type Conversion
1
2
3
4
5
6
7
8
9
10
11
12
| a = 10
print(type(a))
a = float(a)
print(type(a))
a = str(a)
print(type(a))
s = "9.1"
s = float(s)
print(type(s))
|
<class 'int'>
<class 'float'>
<class 'str'>
<class 'float'>
List
1
2
| a = ["1", 1, 2]
b = [2.0, "hello", 4]
|
['1', 1, 2, [2.0, 'hello', 4]]
['1', 1, 2, [2.0, 'hello', 4], 2.0, 'hello', 4]
1
2
3
| a = [1, 2]
b = [2, 3]
a + b
|
[1, 2, 2, 3]
[1, 2, 1, 2]
True
1
2
3
| print(a)
a[0] = 3
print(a)
|
[1, 2]
[3, 2]
Slicing
1
2
| print(a[0:3])
print(a[-4:])
|
[1, 2, 3]
[3, 4, 5, 6]
List memory space
1
2
3
4
5
6
7
8
9
10
| a = [1,2,3]
b = [3,2,1]
b = a # b is pointing at a
print(a)
print(b)
a[0] = 99
print(a)
print(b)
|
[1, 2, 3]
[1, 2, 3]
[99, 2, 3]
[99, 2, 3]
Clone
1
2
3
4
5
6
7
8
| a = [3, 2, 1]
b = [1, 2, 3]
# clone
b = a[:]
a[0] = 100
print(a)
print(b)
|
[100, 2, 1]
[3, 2, 1]
[:] doesn’t work for >= 2-D list! Use .copy() instead
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| a = [[1,2],[3,4]]
b = [[5,6],[7,8]]
b = a[:]
a[0][0] = 100
print(a)
print(b)
import copy
a = [[1,2],[3,4]]
b = [[5,6],[7,8]]
b = copy.deepcopy(a)
a[0][0] = 100
print(a)
print(b)
|
[[100, 2], [3, 4]]
[[100, 2], [3, 4]]
[[100, 2], [3, 4]]
[[1, 2], [3, 4]]
unpacking
1
2
3
| a = [1,2,3]
e1, e2, e3 = a
print(e1, e2, e3)
|
1 2 3