Data Structures in Python: Lists, Tuples, and Dictionaries (Beginner’s Guide)
Introduction
In Python, data structures are used to store and organize data efficiently.
The three most commonly used are:
-
List → Ordered, changeable collection
-
Tuple → Ordered, unchangeable collection
-
Dictionary → Key-value pairs
Mastering these is essential for solving real-world problems and preparing for coding interviews.
1. Python Lists
-
A list is an ordered collection that is mutable (can be changed).
-
Defined using square brackets
[]
.
Example:
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
fruits.append("mango")
print(fruits) # Output: ['apple', 'banana', 'cherry', 'mango']
* Use a list when you need a dynamic collection that can change over time.
2. Python Tuples
-
A tuple is similar to a list but immutable (cannot be changed).
-
Defined using parentheses
()
.
Example:
colors = ("red", "green", "blue")
print(colors[1]) # Output: green
# Trying to modify tuple → Error
# colors[0] = "yellow" #Invalid
<> Use a tuple when you need a fixed collection that should not change.
3. Python Dictionaries
-
A dictionary stores data as key-value pairs.
-
Defined using curly braces
{}
.
Example:
student = {
"name": "Arjun",
"age": 21,
"course": "Computer Science"
}
print(student["name"]) # Output: Arjun
student["age"] = 22 # Update value
print(student)
=>Use a dictionary when you want to map keys to values (like storing student details).
4. Differences Between List, Tuple, and Dictionary
5. Real-World Examples
-
List → Shopping cart items in an e-commerce site
-
Tuple → Latitude & Longitude coordinates (fixed values)
-
Dictionary → Storing user profiles (name, email, password)
Challenge for You
Write a Python program that stores 5 student records using a dictionary.
Each student should have: name
, roll_no
, and marks
.
Print details of the student with the highest marks.,
Summary
-
Use Lists when data changes frequently.
-
Use Tuples when data is constant.
-
Use Dictionaries for mapping key-value pairs.
Understanding these three data structures will make your Python coding much easier and efficient.
Comments
Post a Comment