Tuple Features
1) You can assign values to a tuple without using parentheses/
For example, you can create a tuple like this:
1
2
3
|
a = 1,2,3,4,5
print(a[3]) # 4 An element of a tuple can be accessed in the same way as an element of a list,
# by specifying the element index in square brackets.
|
2) To declare a tuple that includes one single element, you need to use a trailing comma:
1
2
3
4
|
a = 'a'
b = 'b',
print(type(b)) # <class 'tuple'>
print(type(a)) # <class 'str'>
|
3) You can assign the values of the elements of the tuple to individual variables:
1
2
3
|
my_tuple = (1, 2, 3, 4, 5)
a, b, c, d, e = my_tuple
print(c) #3
|
Underscores
_
can be used as unnecessary variables
1
2
3
|
my_tuple = (1, 2, 3)
a, _, _ = my_tuple
print(a) #1
|
Number of variables must match with the number of elements of the tuple!
4) A tuple can contain various nested elements. In this case, when referring to nested elements, you must use additional square brackets
1
2
|
my_tuple = (('a', 'b', 'c'), [1, 2], ((1, 'a' ), ('b', 'c')))
print(my_tuple[2][1]) # ('b', 'c')
|