1# A tuple is a sequence of immutable Python objects. Tuples are
2# sequences, just like lists. The differences between tuples
3# and lists are, the tuples cannot be changed unlike lists and
4# tuples use parentheses, whereas lists use square brackets.
5tup1 = ('physics', 'chemistry', 1997, 2000);
6tup2 = "a", "b", "c", "d";
7
8# To access values in tuple, use the square brackets for
9# slicing along with the index or indices to obtain value
10# available at that index.
11tup1[0] # Output: 'physics'
1my_tuple = 3, 4.6, "dog"
2print(my_tuple)
3
4# tuple unpacking is also possible
5a, b, c = my_tuple
6
7print(a) # 3
8print(b) # 4.6
9print(c) # dog
1my_tuple = ("hello")
2print(type(my_tuple)) # <class 'str'>
3
4# Creating a tuple having one element
5my_tuple = ("hello",)
6print(type(my_tuple)) # <class 'tuple'>
7
8# Parentheses is optional
9my_tuple = "hello",
10print(type(my_tuple)) # <class 'tuple'>
1t = 12345, 54321, 'hello!'
2print(t[0])
3# output 12345
4print(t)
5# output (12345, 54321, 'hello!')
6# Tuples may be nested:
7u = t, (1, 2, 3, 4, 5)
8print(u)
9# output ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
10# Tuples are immutable:
11# assigning value of 12345 to 88888
12t[0] = 88888
13Traceback (most recent call last):
14 File "<stdin>", line 1, in <module>
15TypeError: 'tuple' object does not support item assignment
16# but they can contain mutable objects:
17v = ([1, 2, 3], [3, 2, 1])
18print(v)
19# output ([1, 2, 3], [3, 2, 1])
1 strs = ['ccc', 'aaaa', 'd', 'bb'] print sorted(strs, key=len) ## ['d', 'bb', 'ccc', 'aaaa']
2 #the list will be sorted by the length of each argument