Differences and similarities between tuples and lists in Python?

Both List and Tuple are called Python sequence data types. Objects of both types are a comma-separated collection of objects, not necessarily of the same type.




Similarities

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

 & gt; & gt; & gt; #lis t operations & gt; & gt; & gt; L1 = [1,2,3] & gt; & gt; & gt; L2 = [4,5,6] & gt; & gt; & gt; #concatenation & gt; & gt; & gt; L3 = L1 + L2 & gt; & gt; & gt; L3 [1, 2, 3, 4, 5, 6] & gt; & gt; & gt; #repetition & gt; & gt; & gt; L1 * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3] & gt; & gt; & gt; #indexing & gt; & gt; & gt; L3 [4] 5 & gt; & gt; & gt; #slicing & gt; & gt; & gt; L3 [2: 4] [3, 4] 
 & gt; & gt; & gt; #tuple operations & gt; & gt; & gt; T1 = (1,2,3) & gt; & gt; & gt; T2 = (4,5,6) & gt; & gt; & gt; #concatenation & gt; & gt; & gt; T3 = T1 + T2 & gt; & gt; & gt; T3 (1, 2, 3, 4, 5, 6) & gt; & gt; & gt; #repetition & gt; & gt; & gt; T1 * 3 (1, 2, 3, 1, 2, 3, 1, 2, 3) & gt; & gt; & gt; #indexing & gt; & gt; & gt; T3 [4] 5 & gt; & gt; & gt; #slicing & gt; & gt; & gt; T3 [2: 4] (3, 4) 

The following built-in functions are common to both types



len () &returns the number of elements in a sequence



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

max () &returns the element with the highest value.

 & gt; & gt; & gt; max (L1) 72 & gt; & gt; & gt; max (T1) 72 

min () &returns the element with the lowest value.

 & gt; & gt; & gt; max (T1) 72 & gt; & gt; & gt; min (L1) 16 & gt; & gt; & gt; min (T1) 16 



Differences

The list object is mutable. Therefore, you can add, update or remove an item from the list.

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

A tuple is an immutable object. Any operation that tries to modify it will result in an AttributeError

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







Get Solution for free from DataCamp guru