position: fixed; top: auto !important; margin-left: 112px;

Python Tuple

A tuple is an immutable, ordered list of values. Immutable means you cannot add or remove elements from the tuple.

Difference between List and Tuple

Difference between List and tuple in python is given below,

1) Python tuples are immutable whereas Python list is mutable. You can add or remove elements from the list.

2) Tuples are written using paranthesis whereas the list is written using square brackets.

3) Python tuples are heterogeneous data structures (i.e., their entries have different meanings), whereas Python lists are homogeneous sequences.

4) Tuples are of fixed length whereas List is of variable length.


Python tuple is created using parenthesis().

tupleName = (value1, value2, ..., valueN)


t = (2, 4) print(t)

Access elements from the tuple

t = (2, 4) print(t[0]) #Prints first element print(t[-1]) #Prints first last element print(t[-2]) #Prints second last element
t = (2, 4) print(type(t)) #Prints the type as tuple print(t) #Print the tuple t print(t[0], t[1]) #Print first and second element in tuple print(t[-1]) #Print the first last element

Slicing Python Tuples

Slicing a tuple means to access elements in the given range (start to end).

t = (2, 4, 6, 8, 16) print(t[:0]) #Print the empty tuple print(t[:1]) #Print element till 1 in tuple print(t[1:3]) #1 means to start at 1 and end at 3(do not include third element) in tuple

Using tuple as a key in dictionary

# Using tuple as a key in dictionary d = {(x, x**2) : x for x in range(5)} #Adds elements in dictionary within range 5 in format x, x**2 print(d) #Prints Dictionary print(d[(2,4)]) #Prints element at index [2,4] d[(5,25)] = 5 #update dictionary and adds at first index print(d) del d[(4,16)] #delete operation print(d)

Using tuples in the set

# Using tuples in the set s = {(x, x**2) for x in range(5)} print(s) #Prints elements in the set s.add((5,25)) #Add elemennt in the set print(s) s.remove((4,16)) #Remove element in the set print(s)

Previous Next Article


Largest collection of up-to-date tutorials to learn programming languages. We are focused on easy learning. Massive collection of interview questions one may need for preparation.

Social Profile


Copyright 2018. All rights reserved.