Lists, Tuples, and Dictionaries

1. Introduction

Python provides built-in data structures like lists, tuples, and dictionaries to store and manipulate data efficiently.

Data StructureCharacteristics
ListMutable, ordered, allows duplicates
TupleImmutable, ordered, allows duplicates
DictionaryMutable, key-value pairs, unordered

2. Lists in Python

A list is an ordered collection of elements that can be changed (mutable).

Creating a List

fruits = ["apple", "banana", "cherry"]
print(fruits)

Output

['apple', 'banana', 'cherry']

Accessing List Elements

print(fruits[0])   # First element
print(fruits[-1])  # Last element

Output

apple
cherry

Modifying a List

fruits[1] = "blueberry"
print(fruits)

Output

['apple', 'blueberry', 'cherry']

List Methods

fruits.append("orange")   # Adds at the end
fruits.insert(1, "mango") # Inserts at index 1
fruits.remove("apple")    # Removes "apple"
print(fruits)

Output

['mango', 'blueberry', 'cherry', 'orange']

Looping Through a List

for fruit in fruits:
    print(fruit)

Output

mango
blueberry
cherry
orange

List Slicing

numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])  # Elements from index 1 to 3

Output

[20, 30, 40]

List Comprehension

squares = [x ** 2 for x in range(5)]
print(squares)

Output

[0, 1, 4, 9, 16]

3. Tuples in Python

A tuple is an immutable (unchangeable) ordered collection of elements.

Creating a Tuple

colors = ("red", "green", "blue")
print(colors)

Output

('red', 'green', 'blue')

Accessing Tuple Elements

print(colors[0])   # First element
print(colors[-1])  # Last element

Output

red
blue

Tuple Unpacking

a, b, c = colors
print(a, b, c)

Output

red green blue

Tuple Methods

print(colors.count("red"))  # Counts occurrences
print(colors.index("blue")) # Returns index of "blue"

Output

1
2

4. Dictionaries in Python

A dictionary is an unordered collection of key-value pairs.

Creating a Dictionary

student = {
    "name": "Ankit",
    "age": 25,
    "city": "Delhi"
}
print(student)

Output

{'name': Ankit', 'age': 25, 'city': Delhi'}

Accessing Dictionary Values

print(student["name"])  # Access value using key
print(student.get("age"))  # Alternative way to access value

Output

Ankit
25

Modifying a Dictionary

student["age"] = 26  # Update value
student["gender"] = "Male"  # Add new key-value pair
print(student)

Output

{'name': 'Ankit', 'age': 26, 'city': Delhi', 'gender': 'Male'}

Looping Through a Dictionary

for key, value in student.items():
    print(f"{key}: {value}")

Output

name: Ankit
age: 26
city: Delhi
gender: Male

Dictionary Methods

student.pop("city")  # Removes key "city"
print(student.keys())  # Get all keys
print(student.values())  # Get all values

Output

dict_keys(['name', 'age', 'gender'])
dict_values(Ankit', 26, Male'])

5. Summary

Lists are mutable and allow modifications.
Tuples are immutable and preserve data integrity.
Dictionaries store data as key-value pairs for quick access.