List vs Tuple: Differences

Introduction

The classes of Python data structures are List and Tuple. The tuple has static properties, whereas the list is dynamic. This means that because tuples are static, they are faster than lists because lists can be modified, whereas tuples cannot. Tuples are denoted by parenthesis, while lists are denoted by square brackets.

Important differences between List and Tuple in Python

LIST

TUPLE

Lists are mutable

Tuples are immutable

Iterations in lists are time consuming

Iterations in tuple are faster

The list is better for actions, such as insertion and deletion.

Tuple is appropriate for accessing the elements

Lists consume more memory

Tuple is slightly memory efficient

Lists have several built-in methods

Tuple does not have any built-in methods

Key Differences

Test whether tuples are immutable and list are mutable

Now we will compare mutability between a list and tuples

List Mutability

List = [1, 2, 3, 4, 5, 6]

print("Original list ", List)


List[1] = 10

print("New list ", List)

Output:

Original list  [1, 2, 3, 4, 5, 6]

New list  [1, 10, 3, 4, 5, 6]

Tuple Mutability

Tup = (1, 2, 3)

print("Original Tuple ", Tup)


Tup[1] = 10

print("New Tuple ", Tup)

Output:

Traceback (most recent call last):

  File "./prog.py", line 4, in <module>

TypeError: 'tuple' object does not support item assignment

write your code here: Coding Playground

Test whether tuples are memory efficient

Now we will compare space efficiency between a list and tuples

Example:

import sys

lis = []

tup = ()

lis = ["A", "B"]

tup = ("A", "B")

print(sys.getsizeof(lis))

print(sys.getsizeof(tup))

Output:

72

56

write your code here: Coding Playground