Introduction to Python data structure method three ———— tuples

Source: Internet
Author: User

A python tuple is similar to a list, except that the elements of a tuple cannot be modified. Tuples use parentheses, and tuples are created simply by adding elements in parentheses and separating them with commas, and you need to add a comma after the element when the tuple contains only one element.

The difference between a tuple and a list:

1, the tuple is immutable, the list is variable.

2, the tuple is more secure than the list, and the operation speed is faster.

First, create a tuple

tuple1= (1,2,3,4) tuplt2= (' A ', ' B ', ' C ', ' d ')

Second, access to tuples

A tuple's access is the same as a list, and is accessed using index values.

TUPLE1[1]2TUPLE1[-1] If the index range is exceeded, Python will report an exception. Tuple1[6]traceback (most recent): Python Shell, prompt 4, line 1indexerror:tuple index out of range

Index error: Tuple index out of range

Three, Slice

The slices of the tuple are the same as the list, including only the starting position, not the end position.

Tuple1[0:2] (1, 2)

An empty tuple is returned when the start position of the slice is outside the index range.

Tuple1[5:] ()

Iv. Methods of tuples

Because tuples are not modifiable, there are very few methods for tuples.

The number of occurrences of the 1.count statistic element, returning an integer

T.count (value), integer--return number of occurrences of value

Tuple1.count (1) 1

2.index finding the index position of an element

T.index (value, [Start, [stop]]), integer-return first index of value. Raises valueerror if the value is not present.

Tuple1.index (2) 1

V. Conversion of tuples and lists

1 tuples converted to list print tuple1 (1, 2, 3, 4) test=list (tuple1) print test[1, 2, 3, 4]2. List reload for tuple print test[1, 2, 3, 4]tuple1=tuple (test) PR int Tuple1 (1, 2, 3, 4)


Introduction to Python data structure method three ———— tuples

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.