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

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

  • Both list and tuple are sequence type data types.
  • Both store multiple elements in a single variable.
  • Elements in both of these can be accessed using indexing.

 

Let’s now talk about their differences.

  • Syntax: A list is created using square brackets, whereas, a tuple using parentheses.

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:

  • Mutability: A list is mutable, which means we can make changes to its elements, whereas, a tuple is immutable. Because of a tuple’s static nature, they work much faster than lists.

 

  • Size: As tuples are immutable, Python allocates memory for tuples in terms of larger blocks with low overhead. Whereas, for lists, Python allocates memory in terms of small memory blocks. This size difference is also one of the reasons that make tuples a bit faster than lists, especially when you have a large number of elements. So lists take more memory than tuples.

Example:

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

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

Output:

 

  • Operations:A list has many built-in methods and functions. Here is a list of all of them.

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.

 

Leave a comment