Python provides several data structures to store collections of data. Among these, lists, tuples, and sets are widely used and versatile.
Lists
A list is an ordered, mutable collection of items. It is defined by values between square brackets []
, with items separated by commas.
fruits = ["apple", "banana", "cherry", "date"]
You can access individual items by their index, with the first index being 0.
print(fruits[0]) # prints: apple
Lists are mutable, meaning you can add, remove, or change items after the list’s creation.
fruits[1] = "blueberry" print(fruits) # prints: ['apple', 'blueberry', 'cherry', 'date']
Tuples
Tuples are similar to lists, but they are immutable. This means that after their creation, you can’t change their elements. Tuples are defined by values between parentheses ()
.
dimensions = (1920, 1080)
Just like lists, you can access individual elements by their index:
print(dimensions[0]) # prints: 1920
Attempting to modify an element of a tuple results in a TypeError.
dimensions[0] = 1080 # raises: TypeError
Sets
A set is an unordered, mutable collection of unique elements. It is defined by values between curly braces {}
.
primes = {2, 3, 5, 7, 7, 11} print(primes) # prints: {2, 3, 5, 7, 11}
Notice how the duplicate 7
was removed. Sets are useful for keeping track of unique elements and for set operations (like union, intersection, and difference).
However, because sets are unordered, you can’t access individual elements by their index.
print(primes[0]) # raises: TypeError
Each of these structures has its strengths—lists for ordered, mutable collections; tuples for ordered, immutable collections; and sets for ensuring elements are unique. Understanding these structures is essential for managing data in Python.