+3 votes
in Class 12 by kratos

What is tuple in Python and how can we access values in tuples ?

1 Answer

+4 votes
by kratos
 
Best answer

Tuple is a sequence of immutable Python object. Tuples are sequences, just like

lists. The only difference is that tuples can’t be changed i.e.,tuples are immutable

and tuples use parentheses and lists use square brackets.

Creating a tuple is as simple as putting different comma-separated values and

optionally you can put these comma -separated values between parentheses also.

For example :

tup1 = (‘physics’, ‘chemistry1,1997,2000) ;

tup2 = (1, 2, 3, 4, 5);

tup3 = “a”, “b”, “c”, “d”;

The empty tuple is written as two parentheses containing nothing :

tup1 = ( ) ;

To write a tuple containing a single value you have to include a comma, even

though there is only one

tup1 = (50,);

Like string indices, tuple indices start at 0, and tuples can be sliced, concatenated

and so on. Accessing Values in Tuples :

To access value in tuple, use the square brackets for slicing along with the index

or indices to obtain value available at that index.

Following is a simple example :

!/user/bin/python

tup1 = (‘physics’, ‘chemistry’, 1997,2000);

tup2 = (1, 2, 3,4,5,6, 7);

print “tup1[0]”, tup1[0]

print “tup2[1:5]:”, tup2[1:5]

When the above code is ****, it produces the following result :

tup1[0] : physics

tup2[1:5]: [2, 3,4,5]

...