Tuples
In [1]:
x = () # no-item tuple
In [2]:
len(x)
Out[2]:
In [3]:
type(x)
Out[3]:
In [4]:
y = (1,2,3) # three items
In [5]:
y[2]
Out[5]:
In [6]:
y[-1]
Out[6]:
In [7]:
y[0]
Out[7]:
In [8]:
type(y)
Out[8]:
In [9]:
z = 2, # single-item tuple
In [10]:
z
Out[10]:
In [11]:
len(z)
Out[11]:
In [12]:
list1 = [10, 20, 30]
In [13]:
a = tuple(list1) # tuple from list
a
Out[13]:
And YES, they are IMMUTABLE! Watch it:
In [14]:
a
Out[14]:
In [15]:
del(a[0])
In [16]:
a[0] = 11
In [17]:
a[0]
Out[17]:
But, in the case, a list inside a tuple...
In [18]:
a = ([1, 2], 3)
In [19]:
a
Out[19]:
In [20]:
del(a[0][1]) # a[0][1] is the 1
In [21]:
a
Out[21]:
In [22]:
t = 12345, 54321, 'tuple!'
In [23]:
t
Out[23]:
In [24]:
# tuples may be nested
c = a, (1, 2, 3, 4)
c
Out[24]:
In [25]:
t = 'abc', 1000, 3.14
In [26]:
x, y, z = t # tuple packing
x
Out[26]:
In [32]:
t1 = (10, 20, 30, 100, 1000, 10, 20, 20)
In [33]:
t1.count(10)
Out[33]:
In [34]:
t1.count(20)
Out[34]:
In [35]:
t1.index(10)
Out[35]:
In [36]:
t1.index(100)
Out[36]:
In [37]:
100 in t1
Out[37]:
In [38]:
3 in t1
Out[38]:
In [39]:
3 not in t1
Out[39]:
In [40]:
for name in ('John', 'Mary'):
print('Hello', name)
In [45]:
max(t1)
Out[45]:
In [46]:
min(t1)
Out[46]:
In [47]:
sorted(t1) # return a new sorted list, does not sorte the tuple itself! Remember: immutable!
Out[47]:
In [48]:
t1
Out[48]:
In [49]:
sum(t1)
Out[49]:
In [ ]: