Initialization

t = ()   # an empty tuple

t = ("value1", )   # the comma is mandatory for a single value.
t = "value1",      # same as the above

t = ("value1", "value2")   # t = "value1", "value2"

 

Access

  • The in-operator can be used to check an element exists in a tuple.
print("value1" in t)   # output: True
  • The subscript-operator can be used for accessing an element using the correspoding index. KeyError-exception will be thrown for non-existing indices.
print(d["key1"])   # output: value1
  • Unpack a Tuple
x, y, z = (12, 34, 56)
  • Iteration.
for e in t:
  print(e)

 

Update

  • You cannot insert or modify a tuple since it is immutable.

Methods

  • t.index(element): the index of the element.
  • t.count(element): the count of the element in the tuple.

 

 

Interview Questions


 

1. Difference between list and tuple? Tuples are immutable whereas lists are mutable. The semantic distinction between them is that tuples are heterogeneous data structures while lists are homogeneous sequences. Tuples have structure, lists have order.