How to use python tuples

Tuple-tuple

The list is very suitable for storing data sets that may change during the running of the program.

The list can be modified, but the tuple is unmodifiable

Python calls immutable values that cannot be modified, and immutable lists are called tuples

1. Tuple creation and deletion

(1) Use the assignment operator to directly create a tuple

grammar:

tuplename =(element1, element2, element3,....)

​In Python, tuples use a pair of parentheses to enclose all the elements, but the parentheses are not necessary, as long as a set of values ​​are separated by commas, Python can make it a tuple.

 verse ="Fishing boat singing night","Mountain stream","Water lotus","Han Palace Qiuyue"	#Tuple

​ If there is only one element in the tuple to be created, you need to add a comma after the element, otherwise Python makes it a string.

verse1 =('A piece of ice in the jade pot')	#String
verse2 =('A piece of ice in the jade pot',)	#Tuple

(2) Create an empty tuple

emptytuple =()

(3) Create a numeric tuple

You can use the tuple() function to directly convert the looped result of the range() function into a numeric tuple

tuple(data)

data-Iterable object

(4) Delete tuples

del tuplename

The del statement is not commonly used in actual development, because Python’s built-in garbage collection mechanism will automatically destroy unused tuples, so even if we don’t delete them manually, Python will automatically recycle them.

2. Access tuple elements

Through for loop

coffee_name =('Blue Mountain','Cappuccino','Mandheling','Mocha','Civet','Colombia')print('Hello, welcome~Imi Cafe~\nOur shop has:')for name in coffee_name:print(name,"coffee", end=' ')'''

Output

Hello and welcome~ Yimi Cafe~
My shop has:
Blue Mountain Coffee Cappuccino Coffee Mandheling Coffee Mocha Coffee Civet Coffee Colombian Coffee
”’

for + enumerate()

enumerate():-enumeration

This function is used to combine a traversable data object (such as a list, tuple) into an index sequence, and list data and data subscripts at the same time. It is generally used in a for loop.

team =('rocket','warrior','pioneer','Thunder','Jazz','Spurs')for index, item inenumerate(team):if index %2==0:print(item +'\t\t', end='')else:print(item)

Output

Rocket Warrior
Trailblazer Thunder
Jazz Spurs

3. Modify the elements of the tuple

A tuple is an immutable sequence, so we cannot modify its individual element value. Modified by reassigning tuples.

​Tuples and tuples can be connected, but both of them must be tuples, otherwise it is wrong. When the tuple to be connected has only one element, do not forget the comma.

4. Tuple comprehension

import random
 random_number =(random.randint(10,100)for i inrange(10))
 random_number
< generator object <genexpr  at 0x0000021A177BDED0 	#Generator object
 tuple(random_number)			#Convert to tuple(28,63,34,98,96,36,87,35,25,44)

​It can be seen from the execution results above that the result generated by using the tuple comprehension is not a tuple or list, but a generator object, which is different from the list comprehension.

​To convert the generator object into a tuple, use the tuple() method, and convert it into a list, use the list() method.

Example 1:

# by__next()__Method traversal
# In Python2.x in__next()__The method corresponds to next()Methods are also used to traverse the generator object.
 number =(i for i inrange(3))
 number
< generator object <genexpr  at 0x0000021A1781EA20 
 number.__next__()0
 number.__next__()1
 number.__next__()2
 number.__next__()Traceback(most recent call last):
 File "<pyshell#11 ", line 1,in<module 
 number.__next__()
StopIteration		#Stop iteration

Example 2:

# Traverse through the for loop
 number =(i for i inrange(4))
 number
< generator object <genexpr  at 0x0000021A1781EA98for i in number:print(i, end='')0123print(tuple(number))()

It can be seen from the above two examples: no matter which method of traversal, if you want to use the generator object again, you must recreate a generator object, because the generator object does not exist after the traversal.

5. The difference between tuples and lists

(1) The list is mutable, and the tuple is immutable, unless the whole is replaced.

(2) The list can be added and deleted with append(), extend(), insert(), remove(), pop(), but tuples do not have these methods.

(3) The list supports modification and access through trimming, while tuples only support access, not modification. When no modification is required, it is recommended to use tuples.

(4) Tuples are faster to access and process than lists.

(5) Lists cannot be used as dictionary keys, but tuples can.

The above is the detailed content of the use of python tuples. For more information about the use of python tuples, please pay attention to other related articles on ZaLou.Cn!

Recommended Posts

How to use python tuples
How to use python thread pool
How to use SQLite in Python
How to use PYTHON to crawl news articles
How to use the round function in python
How to use the zip function in Python
How to use the format function in python
How to use code running assistant in python
How to learn python quickly
How to uninstall python plugin
How to understand python objects
How to use Python&#39;s filter function
How to use python&#39;s help function
How to use hanlp in ubuntu
How to write python configuration file
Use python to achieve stepwise regression
How to wrap in python code
How to save the python program
How to omit parentheses in Python
How to install Python 3.8 on CentOS 8
How to install Python 3.8 on Ubuntu 18.04
How to filter numbers in python
How to read Excel in Python
How to install Python on CentOS 8
How to solve python dict garbled
How to view errors in python
How to write return in python
How to view the python module
How to understand variables in Python
How to clear variables in python
How to understand python object-oriented programming
How to verify successful installation of python
How to make a globe with Python
How to delete cache files in python
How to introduce third-party modules in Python
How to represent null values in python
How to save text files in python
Use Python to make airplane war games
How to write win programs in python
How to run id function in python
How to install third-party modules in Python
How to custom catch errors in python
01. Introduction to Python
How to write try statement in python
How to define private attributes in Python
How to use Samba server on Ubuntu 16.04
R&amp;D: How To Install Python 3 on CentOS 7
How to add custom modules in Python
How to process excel table with python
Python crawler-beautifulsoup use
How to understand global variables in Python
How to view installed modules in python
Python novice learns to use the library
How to install Python2 on Ubuntu20.04 ubuntu/focal64
Use Python to quickly cut out images
How to debug python program using repr
How to learn the Python time module
How to open python in different systems
Use python3 to install third on ubuntu
How to sort a dictionary in python
How to get started quickly with Python