"Fifth" in Python learning: tuples in Python and the methods they have

Source: Internet
Author: User

1. Preface

A python tuple (tuple) is similar to a list, except that tuples cannot be modified, that is, once a tuple is created, you cannot add new elements to a tuple, you cannot delete elements in an element, and you cannot modify elements in tuples. But tuples can access any element that can be sliced and iterate through, and tuples can be understood as a read-only list.

2. Creation of tuples

Tuple creation is simple, tuples use parentheses, just add elements in parentheses and separate them with commas.

tup = ('hello' , 'world' , 'china' , 'dog' , 'cat')print(tup)#输出('hello', 'world', 'china', 'dog', 'cat')
3. Accessing elements in a tuple in an indexed manner
tup = ('hello' , 'world' , 'china' , 'dog' , 'cat')print(tup[0])print(tup[1])print(tup[2])#输出'hello''world''china'
Access in slices (package left without packet right)
tup = ('hello' , 'world' , 'china' , 'dog' , 'cat')print(tup[0:3])    #打印索引从0到3的元素,不包含索引为3的元素print(tup[1:])     #打印索引从1开始,一直到列表结束所有元素print(tup[:-1])    #打印索引从0到倒数第2个元素之间的所有元素#输出('hello', 'world', 'china')('world', 'china', 'dog', 'cat')('hello', 'world', 'china', 'dog')
4. Delete a tuple
tup = ('hello' , 'world' , 'china' , 'dog' , 'cat')del tupprint(tup)#输出报错,因为元组已经被删除Traceback (most recent call last):  File "<stdin>", line 1, in <module>NameError: name 'tup' is not defined
5. Meta-Group traversal
tup = ('hello' , 'world' , 'china' , 'dog' , 'cat')for tt in tup:    print(tt)#输出'hello''world''china''dog''cat'

"Fifth" in Python learning: tuples in Python and the methods they have

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.