Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Tuple
In Python programming, a tuple is similar to a list. The difference between the two is that we
cannot change the elements of a tuple once it is assigned whereas in a list, elements can be
changed. Tuples are also comparable and hashable .
To create a tuple with a single element, you have to include the final comma:
>>> t1 = ('a',)
>>> type(t1)
<type 'tuple'>
>>> t2 = ('a')
>>> type(t2)
<type 'str'>
6.2 Accessing values in Tuples
#!/usr/bin/python
tup2 = (1, 2, 3, 4, 5, 6, 7 );
Result:
tup1[0]: physics
tup2[1:5]: (2, 3, 4, 5)
#!/usr/bin/python
# tup1[0] = 100;
print tup3;
#!/usr/bin/python
print tup;
del tup;
print tup;
6.5. Tuple Methods
my_tuple = ('a','p','p','l','e',)
# Count
# Output: 2
print(my_tuple.count('p'))
# Index
# Output: 3
print(my_tuple.index('l'))
# In operation
# Output: True
print('a' in my_tuple)
# Output: False
print('b' in my_tuple)
# Not in operation
# Output: True
6.5.2. Iteration
# Output:
# Hello John
# Hello Kate
print("Hello",name)
all() Return True if all elements of the tuple are true (or if the tuple is empty).
Return True if any element of the tuple is true. If the tuple is empty,
any()
return False.
Return an enumerate object. It contains the index and value of all the items of
enumerate()
tuple as pairs.
Take elements in the tuple and return a new sorted list (does not sort the
sorted()
tuple itself).
Ex:
>>> (0, 1, 2) < (0, 3, 4)
True
>>> (0, 1, 2000000) < (0, 3, 4)
True