2023/1/11 python study notes (tuple)

tuple

Tuples can not only accommodate multiple types of objects like lists, but also have the characteristics of immutable strings.

1Differences between tuples and lists

Lists use square brackets, and tuples use round brackets (you can also use them without brackets)

List elements can be modified but tuples cannot

Methods involving modifying elements in the list are not supported

List comprehensions are called list comprehensions, and tuple comprehensions are called generator expressions.

What 2-tuples and lists have in common

You can use subscripts to get elements

Both support slicing operations

Both support count() method and index() method

Both support the concatenation (+) and repetition (*) operators

All support nesting

Both support iteration

3The importance of parentheses

Increase code readability

4When the tuple has only one element

>>> x = (520,)
>>> x
(520,)
>>> type(x)
<class 'tuple'>

Packing and unpacking of 5-tuples

Generating a tuple is sometimes called tuple packaging.

>>> t = (123, "FishC", 3.14)

The act of assigning them to three variable names at once is called unpacking

>>> x, y, z = t
>>> x
123
>>> y
'FishC'
>>> z
3.14

The truth about assignment

>>> _ = (10, 20)
>>> x, y = _
>>> x
10
>>> y
20

Guess you like

Origin blog.csdn.net/qq_61134394/article/details/128650163