Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

What are the methods of tuple operation in Python

Shulou Source: shulou.com Published: 2022-05-31 11:03:35 10月06日 Update

This article mainly explains "what are the methods of tuple operation in Python". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the methods of tuple operation in Python".

Creation of 1 tuple

1.1. Parentheses can be omitted by creating tuples by ().

A = (1010, 20, 30) or a = 10, 20, 20, 30

If the tuple has only one element, it must be followed by a comma.

This is because the interpreter interprets (1) as an integer 1 and (1,) as a tuple.

> a = (1) > type (a) > a = (1,) # or a = 1, > type (a)

2.2. Create a tuple through tuple ()

Tuple (iterable object) for example: B = tuple () # create an empty tuple object b = tuple ("abc") b = tuple (range (3)) b = tuple

Summary:

Tuple () can receive generating tuples of lists, strings, other sequence types, iterators, and so on.

List () can receive lists generated by tuples, strings, other sequence types, iterators, and so on.

Element access and counting of 2 tuples

11.2 element access and counting of tuples

2.1 elements of tuples cannot be modified

> a = (20, most recent call last 10, 30, 9, 8) > > a [3] = 33Traceback (most recent call last): File ", line 1, in a [3] = 33TypeError: 'tuple' object does not support item assignment

2.2 the element access of the tuple is the same as the list, except that the tuple object is still returned

> a = (20, 10, 10, 10, 10, 10, 9, and 8) > > a [1] 10 > > a [1:3] (10, 10, 30) > > a [: 4] (20, 10, 10, and 30)

3. List the method list.sorted () for sorting is to modify the original list object, and the tuple does not have this method. If you want to rank tuples

Order, you can only use the built-in function sorted (tupleObj) and generate a new list object.

> a = (20, 10, 10, 30, 9, 8) > sorted (a) [8, 9, 10, 20, 30]

3 zip

Zip (listing 1, listing 2.) Combine elements corresponding to multiple lists into tuples and return the zip object

> b = [40pyrrce60] > c = [70pyrrce80] > d = zip (arecedomb) > list (d) [(10,40,70), (20,50,80), (30,60,90)] Thank you for your reading. These are the contents of "what are the methods of tuple operation in Python". After the study of this article, I believe you have a deeper understanding of the methods of tuple operation in Python. The specific use situation still needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Methods elements objects medians learning generation interpretation iterations content characters strings sequences types sorting positions functions but only multiple that is Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker Shulou Information macOS Microsoft MySQL