List, Set and Tuple are three of the core data types in Python. All the three types are used to store collections of data. They are similar in that they can store multiple elements, but they differ in their properties and uses. In this article we will compare the three types on various basis.
Definitions
A list is a mutable collection of ordered elements. They are normally used for storing dynamic information that can change in size, as elements can be added, removed, or modified. Lists can contain any type of data, such as integers, strings, sets, or even other lists.
A set is a mutable collection of unordered, unique elements. A set cannot contain duplicate elements and the elements in a set do not have a specific order. For example, a set {1, 2, 3}
can also be written as {3, 1, 2}
and it will still be considered the same set.
A tuple is an immutable collection of ordered elements. Tuples can contain any type of data, including strings, numbers, lists, and even other tuples. Unlike lists and sets, tuples have a fixed size, meaning that elements cannot be added or removed after the tuple is created.
Syntax
A list is instantiated by enclosing elements within square brackets ([]
). Elements in a list can be of any data type.
A set is defined by enclosing elements within curly braces ({}
). Elements in a set must be hashable, this means that we can't include mutable objects like lists, dictionaries, or sets themselves as elements. Sets also do not support duplicate elements, meaning that if an element is already present in the set, it will not be added again.
A tuple is defined by enclosing elements within parentheses (()
). Like in lists, elements can be of any type.
Mutability
Mutability refers to the ability of an object or data type to be changed or modified. A mutable object allows its values to be modified after it has been created, while an immutable object does not allow any changes to its values after creation.
Lists are mutable, meaning they can be changed after they are created. Elements can be added, removed, or modified. Example:
Similarly, sets are mutable, elements can be added or removed in-place.
Tuples are immutable, they cannot be changed after they are created. Elements cannot be updated, added or removed.
Accessing elements
Lists and tuples supports accessing elements using their indices. This way we can access an element at an arbitrary position.
Both positive indexing and negative indexing is supported in both lists and tuples.
Sets, on the other hand, do not support indexing. Indexing assumes an order in the elements, which sets do not have. Attempting to access an element in a set using an index will raise an error.
Sets are primarily used for membership testing and storing unique elements, rather than accessing specific elements at a particular index. If you need to access a specific element in a set, you can convert it to a list or tuple first.