A Brief Introduction to python Tuples

  • 2021-12-11 18:08:02
  • OfStack

Directory 1, Unpack 2, enumerate3, list ()

Characteristics of tuples: It is an immutable sequence, which cannot be modified once it is created

1. Unpack

Take out the elements of tuples and assign them to different variables


>>> a = ('hello', 'world', 1, 2, 3)
>>> str1, str2, n1, n2, n3 = a
>>> str1
'hello'
>>> str2
'world'
>>> n1
1
>>> n2
2
>>> n3
3
>>> str1, str2, *n = a
>>> str1
'hello'
>>> str2
'world'
>>> n
[1, 2, 3]
>>> str1, _, n1, n2, _ = a
 

2. enumerate

Explanation: Used for tuple traversal to obtain tuple object, the first element is index and the second element is numeric value


a = ('1', 2, 35, 'hello')
for i in enumerate(a):
    print(i)
>>> (0, '1')
>>>    (1, 2)
>>>    (2, 35)
>>>    (3, 'hello')
 

3. list ()

Tuples to lists


Python
a = ('1', 2, 35, 'hello')
print(list(a))
>>> ['1', 2, 35, 'hello']

Related articles: