What is a List?
So far you've stored one value in one variable:
What if you have 100 students? You can't create 100 variables. That's where Lists come in.
A list stores multiple values in a single variable:
Done. 3 students in one variable. Scale this to 100 or 1000 — same concept.
Creating a List
Output:
['apple', 'banana', 'mango', 'orange']
[85, 90, 78, 92, 88]
Indexing — Accessing Items
Every item in a list has a position called index. Indexing starts from 0 in Python:
Negative Indexing
Python also allows counting from the end using negative numbers:
Very useful when you want the last item and don't know the length of the list.
Slicing — Getting a Portion of a List
You can extract a section of a list using [start:end]:
Same rule as range — end index is not included.
Modifying Items
Lists are mutable — you can change their values after creation:
List Methods — Built-in Operations
Python gives you many built-in methods to work with lists:
Adding Items
Removing Items
Other Useful Methods
Checking if Item Exists
Looping Through a List
This is where lists really shine — combine with for loops:
Output:
apple
banana
mango
orange
With index using enumerate():
fruits = ["apple", "banana", "mango"]
for index, fruit in enumerate(fruits):
print(f"{index + 1}. {fruit}")
Output:
1. apple
2. banana
3. mango
enumerate() gives you both the index and the value at the same time. Very useful.
List with Functions — Practical Example
def get_total(marks):
total = 0
for mark in marks:
total += mark
return total
def get_average(marks):
return get_total(marks) / len(marks)
def get_highest(marks):
return max(marks)
def get_lowest(marks):
return min(marks)
marks = [85, 90, 78, 92, 88, 76]
print(f"Marks: {marks}")
print(f"Total: {get_total(marks)}")
print(f"Average: {get_average(marks):.2f}")
print(f"Highest: {get_highest(marks)}")
print(f"Lowest: {get_lowest(marks)}")
Output:
Marks: [85, 90, 78, 92, 88, 76]
Total: 509
Average: 84.83
Highest: 92
Lowest: 76
List of Lists — 2D List
A list can contain other lists. This is like a table with rows and columns:
students = [
["Rahul", 85, "A"],
["Priya", 92, "A+"],
["Gagan", 78, "B"]
]
# Accessing
print(students[0]) # ['Rahul', 85, 'A']
print(students[0][0]) # Rahul (row 0, column 0)
print(students[1][1]) # 92 (row 1, column 1)
# Looping
for student in students:
print(f"Name: {student[0]}, Marks: {student[1]}, Grade: {student[2]}")
Output:
Name: Rahul, Marks: 85, Grade: A
Name: Priya, Marks: 92, Grade: A+
Name: Gagan, Marks: 78, Grade: B
Common Mistake — Copying a List
This is a classic beginner trap:
list1 = [1, 2, 3]
list2 = list1 # this is NOT a copy — both point to same list
list2.append(4)
print(list1) # [1, 2, 3, 4] — list1 also changed!
print(list2) # [1, 2, 3, 4]
To make a proper independent copy:
list1 = [1, 2, 3]
list2 = list1.copy() # proper copy
list2.append(4)
print(list1) # [1, 2, 3] — unchanged
print(list2) # [1, 2, 3, 4]
Real World Example — Shopping Cart
cart = []
def show_cart():
if len(cart) == 0:
print("Cart is empty")
else:
print("\n=== Your Cart ===")
for index, item in enumerate(cart):
print(f"{index + 1}. {item}")
print(f"Total items: {len(cart)}")
def add_item():
item = input("Enter item name: ")
cart.append(item)
print(f"{item} added to cart!")
def remove_item():
show_cart()
if len(cart) > 0:
item = input("Enter item to remove: ")
if item in cart:
cart.remove(item)
print(f"{item} removed!")
else:
print("Item not found in cart")
while True:
print("\n=== Shopping Cart ===")
print("1. Add item")
print("2. Remove item")
print("3. View cart")
print("4. Exit")
choice = input("Enter choice: ")
if choice == "1":
add_item()
elif choice == "2":
remove_item()
elif choice == "3":
show_cart()
elif choice == "4":
print("Thank you for shopping!")
break
else:
print("Invalid choice")
This is a real mini-application — using everything you've learned so far together.
Quick Reference — All List Methods
fruits = ["apple", "banana", "mango"]
fruits.append("orange") # add to end
fruits.insert(1, "grapes") # add at index
fruits.remove("banana") # remove by value
fruits.pop() # remove last
fruits.pop(0) # remove by index
fruits.sort() # sort ascending
fruits.reverse() # reverse
fruits.clear() # remove all items
fruits.copy() # make a copy
len(fruits) # count items
"apple" in fruits # check existence
fruits.index("mango") # find index of value
fruits.count("apple") # count occurrences
Exercise 🏋️
Build a Number Analyzer program:
- Ask user to enter 5 numbers one by one and store them in a list
- Then display:
- All numbers
- Sum of all numbers
- Average
- Highest number
- Lowest number
- All even numbers from the list
- All odd numbers from the list
- List sorted in ascending order
Expected output:
Enter number 1: 15
Enter number 2: 8
Enter number 3: 23
Enter number 4: 4
Enter number 5: 16
=== Analysis ===
Numbers: [15, 8, 23, 4, 16]
Sum: 66
Average: 13.20
Highest: 23
Lowest: 4
Even numbers: [8, 4, 16]
Odd numbers: [15, 23]
Sorted: [4, 8, 15, 16, 23]
Hint: Use a for loop to collect numbers, and another for loop to separate even and odd numbers into two separate lists.
Jab ho jaye, "Next" likho — aur hum Tuples aur Dictionaries sikhenge! Dictionary especially bahut important hai — real world apps me har jagah use hoti hai! 🚀
No comments:
Post a Comment