forked from huangsam/ultimate-python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtuple.py
More file actions
Latest commit
47 lines (38 loc) · 1.43 KB
/
Copy pathtuple.py
File metadata and controls
47 lines (38 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
"""
Tuples are an ordered collection of values that cannot be modified at
runtime. This module shows how tuples are created, iterated, accessed
and combined.
"""
defmain() ->None:
# This is a tuple of integers
immutable= (1, 2, 3, 4)
# It can be indexed like a list
assertimmutable[0] ==1
assertimmutable[-1] ==4
# It can be sliced like a list
assertimmutable[1:3] == (2, 3)
assertimmutable[3:4] == (4,)
assertimmutable[1::2] == (2, 4)
assertimmutable[::-1] == (4, 3, 2, 1)
# It can be iterated over like a list
forix, numberinenumerate(immutable):
assertimmutable[ix] ==number
# But its contents cannot be changed. As an alternative, we can
# create new tuples from existing tuples
bigger_immutable=immutable+ (5, 6)
assertbigger_immutable== (1, 2, 3, 4, 5, 6)
smaller_immutable=immutable[0:2]
assertsmaller_immutable== (1, 2)
# We use tuples when the number of items is consistent. An example
# where this can help is a 2D game with X and Y coordinates. Using a
# tuple with two numbers can ensure that the number of coordinates
# doesn't change to one, three, four, etc.
moved_count=0
pos_x, pos_y= (0, 0)
foriinrange(1, 5, 2):
moved_count+=1
pos_x, pos_y= (pos_x+10*i, pos_y+15*i)
assertmoved_count==2
assertpos_x==40andpos_y==60
if__name__=="__main__":
main()