-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtupleT.py
More file actions
112 lines (80 loc) · 2.73 KB
/
Copy pathtupleT.py
File metadata and controls
112 lines (80 loc) · 2.73 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# tupleT.py
# -------------------------------
# CREATING TUPLES
# -------------------------------
t1 = (1, 2, 3) # normal tuple
t2 = ('a', 'b', 'c')
t3 = (5,) # single element tuple (comma is required)
t4 = 5, # also tuple without parentheses
print(type(t3)) # <class 'tuple'>
# -------------------------------
# ACCESSING VALUES IN TUPLES
# -------------------------------
t = ('spam', 'Spam', 'SPAM!')
print(t[0]) # spam (index starts at 0)
print(t[2]) # SPAM!
print(t[-1]) # SPAM! (last element)
print(t[-2]) # Spam
# -------------------------------
# SLICING TUPLES
# -------------------------------
print(t[1:]) # ('Spam', 'SPAM!')
print(t[:2]) # ('spam', 'Spam')
print(t[:]) # full tuple
print(t[::-1]) # reverse tuple
# -------------------------------
# UPDATING TUPLES (IMMUTABLE)
# -------------------------------
# t[0] = 'new' # ERROR: tuples are immutable
# workaround: create new tuple
t_new = ('new',) + t[1:]
print(t_new) # ('new', 'Spam', 'SPAM!')
# -------------------------------
# DELETE TUPLE ELEMENTS
# -------------------------------
# del t[0] # ERROR: cannot delete individual element
# delete entire tuple
temp = (1, 2, 3)
del temp # tuple deleted
# print(temp) # ERROR: temp is not defined
# -------------------------------
# TUPLE OPERATIONS
# -------------------------------
# concatenation
print((1, 2, 3) + (4, 5, 6)) # (1, 2, 3, 4, 5, 6)
# repetition
print(('Hi!',) * 4) # ('Hi!', 'Hi!', 'Hi!', 'Hi!')
# membership
print(3 in (1, 2, 3)) # True
print(5 not in (1, 2, 3)) # True
# -------------------------------
# NO ENCLOSING DELIMITERS
# -------------------------------
print('abc', -4.24e93, 18+6.6j, 'xyz') # tuple-like output
x, y = 1, 2 # tuple unpacking
print("Value of x , y :", x, y)
# -------------------------------
# INDEXING EXAMPLE
# -------------------------------
L = ('spam', 'Spam', 'SPAM!')
print(L[2]) # SPAM!
print(L[-2]) # Spam
print(L[1:]) # ('Spam', 'SPAM!')
# -------------------------------
# BUILT-IN FUNCTIONS WITH TUPLES
# -------------------------------
t = (10, 20, 30, 5)
print(len(t)) # 4
print(max(t)) # 30
print(min(t)) # 5
# convert list to tuple
lst = [1, 2, 3]
tup = tuple(lst)
print(tup) # (1, 2, 3)
# -------------------------------
# NOTE ON cmp()
# -------------------------------
# cmp() is NOT available in Python 3
# Instead, use comparison operators:
print((1, 2, 3) == (1, 2, 3)) # True
print((1, 2, 3) < (1, 2, 4)) # True