In Python, Lists and Tuples are two fundamental data structures used to store collections of items.
While both can hold multiple values, they differ mainly in mutability — lists are mutable (changeable), while tuples are immutable (unchangeable).
Lists in Python
A list is an ordered collection of elements, which can be of any data type — integers, strings, floats, or even other lists. Lists are created using [ ] (square brackets).
Example:
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [10, "Python", 3.14, True]
You can access elements in a list using indexing (starting from 0).
print(fruits[0])
print(fruits[-1])
List Operations
Python provides several operations to manipulate lists.
Example:
fruits = ["apple", "banana", "cherry"]
print(fruits)
numbers = [5, 2, 9, 1]
print(numbers)
fruits.append("mango")
print(fruits)
fruits.insert(1, "orange")
print(fruits)
fruits.extend(["grape", "melon"])
print(fruits)
fruits.remove("banana")
print(fruits)
popped_item = fruits.pop()
print(fruits, "|", popped_item)
numbers.sort()
print(numbers)
numbers.reverse()
print(numbers)
fruits.clear()
print(fruits)
Indexing and Slicing
Lists support indexing and slicing similar to strings.
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])
print(numbers[:3])
print(numbers[-2:])
You can also use nested lists:
data = [[1, 2], [3, 4], [5, 6]]
print(data[1][0])
Tuples in Python
A tuple is similar to a list but immutable. Once created, its elements cannot be modified. Tuples are defined using ( ) (parentheses).
Example:
colors = ("red", "green", "blue")
print(colors[0])
Attempting to modify a tuple will cause an error:
colors[1] = "yellow"
The immutability of tuples makes them faster and safer when working with fixed data that should not change. This feature is often used in constants, dictionary keys, and function returns.
Tuple Unpacking
Tuple unpacking allows you to assign tuple elements to multiple variables in one step.
Example:
person = ("Alice", 25, "Engineer")
name, age, profession = person
print(name)
print(age)
print(profession)
You can also use the * operator for variable-length unpacking:
numbers = (1, 2, 3, 4, 5)
a, *b, c = numbers
print(a)
print(b)
print(c)
Summary
Lists and Tuples are core building blocks in Python programming. While lists offer flexibility and mutability for dynamic data, tuples ensure stability and efficiency for fixed data.
In the next article, we'll explore Dictionaries and Sets — two powerful data structures for mapping and storing unique elements efficiently.
Comments
No comments yet. Ask a question or share what helped.