What are the differences and similarities between tuples and lists in Python?


Both List and Tuple are called as sequence data types of Python. Objects of both types are comma separated collection of items not necessarily of same type.

Similarities

Concatenation, repetition, indexing and slicing can be done on objects of both types

>>> #list operations
>>> L1=[1,2,3]
>>> L2=[4,5,6]
>>> #concatenation
>>> L3=L1+L2
>>> L3
[1, 2, 3, 4, 5, 6]
>>> #repetition
>>> L1*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> #indexing
>>> L3[4]
5
>>> #slicing
>>> L3[2:4]
[3, 4]


>>> #tuple operations
>>> T1=(1,2,3)
>>> T2=(4,5,6)
>>> #concatenation
>>> T3=T1+T2
>>> T3
(1, 2, 3, 4, 5, 6)
>>> #repetition
>>> T1*3
(1, 2, 3, 1, 2, 3, 1, 2, 3)
>>> #indexing
>>> T3[4]
5
>>> #slicing
>>> T3[2:4]
(3, 4)

Following built-in functions are common to both types

len() − return number of elements in sequence

>>> L1=[45,32,16,72,24]
>>> len(L1)
5
>>> T1=(45,32,16,72,24)
>>> len(T3)

max() − returns element with largest value.

>>> max(L1)
72
>>> max(T1)
72

min() − returns element with smallest value.

>>> max(T1)
72
>>> min(L1)
16
>>> min(T1)
16

Differences

List object is mutable. Hence, it is possible to append, update or delete an item from list.

>>> L1=[45,32,16,72,24]
>>> L1.append(56)
>>> L1
[45, 32, 16, 72, 24, 56]
>>> L1.insert(4,10) #insert 10 at 4th index
>>> L1
[45, 32, 16, 72, 10, 24, 56]
>>> L1.remove(16)
>>> L1
[45, 32, 72, 10, 24, 56]
>>> L1[2]=100 #update
>>> L1
[45, 32, 100, 10, 24, 56]

Tuple is immutable object. Any operation that try to modify it , results in AttributeError

T1.append(56)
AttributeError: 'tuple' object has no attribute 'append'
>>> T1.remove(16)
AttributeError: 'tuple' object has no attribute 'remove'
>>> T1[2]=100
TypeError: 'tuple' object does not support item assignment


Updated on: 20-Feb-2020

654 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements