In Python, Tuples and Lists are both used to store collections of elements, but they have some key differences in terms of mutability, performance, and intended use cases.
Tuple and List can store objects of any data type, includes null data type defined by the None Keyword as well.
A tuple is an ordered collection of elements, similar to a list, but unlike lists, tuples are immutable, meaning their elements cannot be changed after creation. Tuples are created using parentheses ().
# Declaration of Tuple your_tuple = (1, 2, 3, 4, 5, 6, 7) # Printing Tuple variable print(your_tuple) # Output: (1, 2, 3, 4, 5, 6, 7) # Checking Type of Variable print(type(your_tuple)) # Output: <class 'tuple'>
List is a versatile and commonly used data structure that stores a collection of elements. Lists are mutable, meaning their elements can be changed after creation.
# Declaration of List your_tuple = [1, 2, 3, 4, 5, 6, 7] # Printing List variable print(your_tuple) # Output: [1, 2, 3, 4, 5, 6, 7] # Checking Type of Variable print(type(your_tuple)) # Output: <class 'list'>
They can hold elements of different data types, and the elements can be accessed using their indices. Lists are created using square brackets [].
Tuples are immutable, meaning once they are created, their elements cannot be changed, added, or removed.
your_tuple = (1, 2, 3) your_tuple[0] = 10 # Raises TypeError: 'tuple' object does not support item assignment your_list = [1, 2, 3] your_list[0] = 10 # Modifies the first element of the list
Lists are mutable, meaning you can modify their elements after creation, add new elements, or remove existing elements.
# Tuples for fixed collections coordinates = (10, 20) person_info = ('Alice', 25) # Lists for mutable collections numbers = [1, 2, 3, 4, 5, 6] names = ['Alice', 'Emma', 'Charlie']
Tuples are commonly used for storing fixed collections of items where immutability is desired, such as coordinates, database records, function return values, and keys in dictionaries (since they need to be hashable).
Lists are used when you need a mutable collection of items that can be modified, such as sequences of data that may change over time, or when we need to perform operations like sorting, appending, or removing elements.
Tuples are generally more memory-efficient and have slightly faster performance compared to lists because they are immutable and their size cannot change after creation.
Lists require more memory and may have slower performance, especially when appending or removing elements, due to their mutable nature and the need for dynamic resizing.