Python Tuple - Codzify.com

2 min read Basic


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.

Syntax

Python tuple is created using parenthesis().

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

Example

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)

How was the tutorial? Nice. Right?



Deep Concept videos to crack the highly-piad interviews.

Chekout out our Youtube Channel to get detailed video content on important topics in interviews.



What is your Interview Score?

Test your skillset with the curated questions created by experts around the globe.

Book a free test slot. Now !.

It usually takes 30 mins for an online test and this test will be MCQ based. Get detailed analytics based on your test and recommedations with personalised roadmaps.

Book a test slot. Now!

Have questions about the trial coding class?

Chat with our experts to discuss

Connect on WhatsApp


Recommended tutorials

#online compiler for c     #python for programming    

#dfs and bfs algorithm     #programming with c language

#storageclass in C    #listcomprehension in python