Python Working With Tuple Data Type

Python Working With Tuple Data Type

Tuple is a sequential data structure in python. It is a immutable data type so, we cannot make any modifications to the tuple once created. Tuple stores the data in a sequential manner. we can access the data in the tuple with indexes. Form the from index starts from 0, 1,2, 3, etc. Tuple also supports negative indexing. Form the rear the index starts from -1, -2, etc.

Advantages of tuples

  • In general tuples are faster than the lists.
  • Tuples are write protected so, use it when you are defining the write protected data in your programs.
  • Tuple can store heterogeneous data types.

How to creat tuple in python ?

# with builtin tuple function
t = (1,2,3 "hello")
# or simply
t = 1,2,3,4, "hello"
print(t)
# Output: (1,2,3,4, "hello")
t = 1
print(type(t))
# Output: <type int>
# tuple Trick
t = 1,
print(type(t))
# Output: <type 'tuple'>

Try above code in python interpreter to know how to create tuple in a simpler way. we can also use a python builtin function "tuple" to convert any sequential data type into a tuple.

Using "tuple" builtin function

# lets convert the string into a tuple
s = "hello world"
t = tuple(s)
print(t)
# Output: ('h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd')
# lets convert the list into a tuple
lst = ["Anju", 223, {1: 2}]
t = tuple(lst)
print(t)
# Output: ('Anju', 223, {1: 2})
# lets convert the dict into a tuple
d = {"tuple": (1,2,4), "list": ["hi", 2]}
t = tuple(d)
print(t)
# Output: ('list', 'tuple')

Execute the above code in python interpreter. In above code we have converted the string, list and dict into a tuple. But, If we observe we can find that when converting the dictionary into the tuple the result contains only the keys of the dictionary/dict.

Working with tuple in python

  • get an value of an element in a tuple with an index
t = (1,2,3,4, "hi", 1,2,3,4,5)
out = t[4] # 4 is index value of "hi"
print(out)
# Output: hi
out = t[-4]
print(out)
# Output: 2
  • get a tuple item with an index number
# method signature: T.index(value) --> int
t = (1,2,3,4, "hi", 1,2,3,4,5)
index = t.index(4) # item
print(index)
# Output: 3
  • count the number of occurrences of an element in a tuple with method "count"
# method signature: T.count(value) --> int
t = (1,2,3,4, "hi", 1,2,3,4,5)
count = t.count(1) # element = 1
print(count)
# Output: 2
  • slice operation on a tuple
# Signature: T[start_index:end_index]
t = (1,2,3,4, "hi", 1,2,3,4,5)
out = t[3:7]
print(out)
# Output: (4, 'hi', 1, 2)
  • add tuple "t1" and tuple "t2" ("+" operation on tuple data)
t1 = (1,2,3,4, "hi")
t2 = (3,4)
out = t1 + t2
print(out)
# Output: (1, 2, 3, 4, 'hi', 3, 4)
  • Multiplication operator on python
t = (1,2,3,4, "hi")
out = t * 2
print(out)
# output: (1, 2, 3, 4, 'hi', 1, 2, 3, 4, 'hi')

Reference: