Python provides built-in data structures like lists, tuples, and dictionaries to store and manipulate data efficiently.
| Data Structure | Characteristics |
|---|---|
| List | Mutable, ordered, allows duplicates |
| Tuple | Immutable, ordered, allows duplicates |
| Dictionary | Mutable, key-value pairs, unordered |
A list is an ordered collection of elements that can be changed (mutable).
fruits = ["apple", "banana", "cherry"]
print(fruits)['apple', 'banana', 'cherry']print(fruits[0]) # First element
print(fruits[-1]) # Last elementapple
cherryfruits[1] = "blueberry"
print(fruits)['apple', 'blueberry', 'cherry']fruits.append("orange") # Adds at the end
fruits.insert(1, "mango") # Inserts at index 1
fruits.remove("apple") # Removes "apple"
print(fruits)['mango', 'blueberry', 'cherry', 'orange']for fruit in fruits:
print(fruit)mango
blueberry
cherry
orangenumbers = [10, 20, 30, 40, 50]
print(numbers[1:4]) # Elements from index 1 to 3[20, 30, 40]squares = [x ** 2 for x in range(5)]
print(squares)[0, 1, 4, 9, 16]A tuple is an immutable (unchangeable) ordered collection of elements.
colors = ("red", "green", "blue")
print(colors)('red', 'green', 'blue')print(colors[0]) # First element
print(colors[-1]) # Last elementred
bluea, b, c = colors
print(a, b, c)red green blueprint(colors.count("red")) # Counts occurrences
print(colors.index("blue")) # Returns index of "blue"1
2A dictionary is an unordered collection of key-value pairs.
student = {
"name": "Ankit",
"age": 25,
"city": "Delhi"
}
print(student){'name': Ankit', 'age': 25, 'city': Delhi'}print(student["name"]) # Access value using key
print(student.get("age")) # Alternative way to access valueAnkit
25student["age"] = 26 # Update value
student["gender"] = "Male" # Add new key-value pair
print(student){'name': 'Ankit', 'age': 26, 'city': Delhi', 'gender': 'Male'}for key, value in student.items():
print(f"{key}: {value}")name: Ankit
age: 26
city: Delhi
gender: Malestudent.pop("city") # Removes key "city"
print(student.keys()) # Get all keys
print(student.values()) # Get all valuesdict_keys(['name', 'age', 'gender'])
dict_values(Ankit', 26, Male'])Lists are mutable and allow modifications.
Tuples are immutable and preserve data integrity.
Dictionaries store data as key-value pairs for quick access.
Sign in to join the discussion and post comments.
Sign inPython for Web Development
Python for Web Development is a comprehensive tutorial series covering the fundamentals of building web applications using Flask and Django. From setting up a project to working with databases, authentication, REST APIs, and deployment on cloud platforms, this series provides a solid foundation for developing secure and scalable web applications.
Object-Oriented Programming (OOP) in Python
Learn the fundamentals of Object-Oriented Programming (OOP) in Python, including classes, objects, inheritance, polymorphism, encapsulation, and more. Understand how OOP enhances code reusability, scalability, and organization.