tuple

Python's tuples are similar to lists, except that the elements of the tuple cannot be modified.

Tuples use parentheses and lists use square brackets.

Tuple creation is simple, just add elements to the parentheses and separate them with commas.

Example below:

Instance (Python 2.0+)

tup1 = ('physics' , 'chemistry', 1997 , 2000) tup2 = (< Span class="hl-number">1, 2, 3, 4 , 5 ) tup3= "< Span class="hl-string">a", "b", "c"< Span class="hl-code">, "d"

Create an empty tuple

tup1 = ()

When a tuple contains only one element, you need to add a comma after the element

tup1 = (50,)

The tuple is similar to a string. The index of the subscript starts from 0 and can be intercepted, combined, and so on.


Access tuple

Tuples can use subscript indexes to access values ​​in tuples, as in the following example:

Instance (Python 2.0+)

#!/usr/bin/python tup1 = (< Span class="hl-quotes">'physics', 'chemistry' , 1997, < Span class="hl-number">2000) tup2 = (< Span class="hl-number">1, 2, 3, 4 , 5, < Span class="hl-number">6, 7 ) print "tup1[0]: ", tup1[0] print "tup2[1:5]: ", < Span class="hl-identifier">tup2[1:5]

The output of the above example:

tup1[0]: physics
tup2[1:5]: (2, 3, 4, 5)

Modify the tuple

The element values in the tuple are not allowed to be modified, but we can combine the tuples, as in the following example:

Instance(Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- tup1 = (12, 34.56) tup2 = ('abc', 'xyz') # The following modification of tuple element operations is illegal。 # tup1[0] = 100 # Create a new tuple tup3 = tup1 + tup2 print tup3





javacodegeeks is optimized for learning. javacodegeeks
All Right Reserved and you agree to have read and accepted our term and condition.