Online Classes

Results can only be achieved if you have the focused direction and crystal clear knowledge. To achieve this, you need a mentor. We will help you out by connecting with an expert mentor in the field.

Learn More


Python Tuple -

2 min read

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)

Try to execute what you have learnt

Easy to use online data structure compiler where you can execute the programs in your favourite programming language.
(C, C++, Python)

Open Compiler

HTML, CSS and Javascript Real time Web Editor

Execute your HTML, CSS and javascript code in real time with the web editor
(HTML, CSS, Bootstrap, Javascript)

Open Web Editor