i2tutorials

What’s the difference between lists and tuples in python?

 

Although there are many differences between lists and tuples, there are some similarities too between them

 

Let’s now talk about their differences.

Example:

tuple_name= ('Red', 'Orange', 'Black')
list_name= ['Red', 'Orange', 'Black']

Output:

 

We can check the type of tuple_name and list_name using the type() function and know the difference.

Example:

tuple_name= ('Red', 'Orange', 'Black')
list_name= ['Red', 'Orange', 'Black']

print(type(tuple_name))
print(type(list_name))

Output:

 

Example:

tuple_name= ('Red', 'Orange', 'Black')
list_name= ['Red', 'Orange', 'Black']

print(tuple_name.__sizeof__())
print(list_name.__sizeof__())

Output:

 

Example:

dir(list_name)

output:

 

['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__iadd__',
 '__imul__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__rmul__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'append',
 'clear',
 'copy',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort']

 

A tuple has the below in-built functions. We can clearly see that list directory has more functionalities like insert, pop, delete etc, which tuple isn’t having.

Example:

dir(tuple_name)

Output:

 

A list is a heterogeneous sequence, which means we can have elements of different types in it, whereas, a tuple is a homogeneous sequence. Lists have a variable length as they are mutable, whereas, tuples have fixed lengths as they are immutable and can’t make any changes.

 

Exit mobile version