forked from sangam92/python_tutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtuples.py
152 lines (70 loc) · 2.04 KB
/
tuples.py
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#Tuples are immutable sequence of an element.
#They can be represented by the parenthesis ().
#The element contained in the tuple can be of any datatypes.
#1.) How to initialize a tuple ?
#empty tuple
a =()
#Tuple with values.
a =(2,"san",6)
#Tuple with one value.
#The Tuple with single value should have a comma.
a= (5,)
#2.) Accessing values in tuple.
#The value in tuple can be accessed via indexing and slicing.
#The value in the tuple starts from the zero index.
#Example :-
a =(2,"san",6,7,9)
print(a[2])
# The Output will be 6.
print(a[0])
# The Output will be 2.
print(a[2:4])
# The Output will be 6,7.
#3.) Nested Tuples.
#We can have a tuple inside a tuple but to access this is a tricky one.
nestedtuple = (2,3,(4,6,7))
print(nestedtuple[2])
# The output will be (4,6,7).
nestedtuple = (2,3,(4,6,(3,5),7))
print(nestedtuple[2][0])
#The output will be 4.
#Negative Indexing:
nestedtuple = (2,3,(4,6,(3,5),7))
print(nestedtuple[-2]
# The Output will be 3.
#Slicing a tuple:
a =(2,"san",6,7,9)
print(a[2:4])
#The output is 6,7
print(a[:3])
#The output is(2, 'san', 6).
print(a[:])
#The output is (2,"san",6,7,9)
print(a[:-1])
(2, 'san', 6, 7)
# The tuples are immutable but if the element inside tuple is mutable .it can be changed.
a =(2,"san",6,7,9)
a[2]= 4
#we get the below error;
#TypeError: 'tuple' object does not support item assignment.
#but in case of a list ,the result is different.
my_tuple = (4, 2, 3, [6, 5])
my_tuple[3][1]=9
print(my_tuple)
#The output is (4, 2, 3, [6, 9]).
#deleting a tuple.
my_tuple = (4, 2, 3, [6, 5])
del my_tuple
print(my_tuple)
# The output is NameError: name 'my_tuple' is not defined.
#concatenation of Tuples.
a =(2,3,4)
b =(4,5,6)
print(a + b)
# The output is (2, 3, 4, 4, 5, 6)
a =(2,3,4,4,5)
print(a.count(4))
# The output is 2.
a =(2,3,4,4,5)
print(a.index(3))
# The output is 1.