Learn Python in 30 Days - Day 7: Lists in Python
Welcome to Day 7! Today, we’ll dive into lists, one of the most versatile and commonly used data structures in Python. Lists allow you to store and manipulate multiple items in a single variable. Let’s explore how to use them effectively!
1. What is a List?
A list is an ordered collection of items (of any data type) in Python. Lists are:
- Mutable (you can change them).
- Indexed (you can access elements by their position).
- Versatile (can store different data types in the same list).
Example:
my_list = ["apple", "banana", "cherry"]
2. Creating Lists
Example:
# A list of strings
names = ["Farjana Akter Mim", "Rahim", "Karim"]
# A list of integers
ages = [21, 25, 30]
# A mixed list
mixed = ["Brahmanbaria", 21, True]
# An empty list
empty = []
3. Accessing Elements
Use indexing to access elements in a list. Indexing starts at 0
.
Example:
names = ["Farjana Akter Mim", "Rahim", "Karim"]
# First element
print(names[0]) # Output: Farjana Akter Mim
# Last element
print(names[-1]) # Output: Karim
4. Modifying Lists
You can update, add, or remove elements from a list.
Updating Elements:
names = ["Farjana Akter Mim", "Rahim", "Karim"]
names[1] = "Abdul"
print(names) # Output: ['Farjana Akter Mim', 'Abdul', 'Karim']
Adding Elements:
- Using
append()
: Adds an element to the end of the list. - Using
insert()
: Adds an element at a specific position.
names = ["Farjana Akter Mim", "Rahim"]
names.append("Karim")
print(names) # Output: ['Farjana Akter Mim', 'Rahim', 'Karim']
names.insert(1, "Nusrat")
print(names) # Output: ['Farjana Akter Mim', 'Nusrat', 'Rahim', 'Karim']
Removing Elements:
- Using
remove()
: Removes a specific value. - Using
pop()
: Removes an element by index and returns it. - Using
del
: Deletes an element or the entire list.
names = ["Farjana Akter Mim", "Rahim", "Karim"]
names.remove("Rahim")
print(names) # Output: ['Farjana Akter Mim', 'Karim']
removed = names.pop(0)
print(removed) # Output: Farjana Akter Mim
print(names) # Output: ['Karim']
del names[0]
print(names) # Output: []
5. Iterating Over Lists
Use a for loop to iterate over a list.
Example:
names = ["Farjana Akter Mim", "Rahim", "Karim"]
for name in names:
print(name)
Output:
Farjana Akter Mim
Rahim
Karim
6. Common List Operations
Operation | Code Example | Output |
---|---|---|
Length of a list | len(names) |
3 |
Check if item exists | "Rahim" in names |
True |
Sorting a list | names.sort() |
Sorted list alphabetically |
Reverse a list | names.reverse() |
List in reverse order |
Copy a list | new_list = names.copy() |
A new copy of the list |
7. Slicing Lists
You can extract a portion of a list using slicing.
Syntax:
list[start:end] # Elements from 'start' to 'end-1'
Example:
names = ["Farjana Akter Mim", "Rahim", "Karim", "Nusrat", "Habib"]
# Get first three elements
print(names[0:3]) # Output: ['Farjana Akter Mim', 'Rahim', 'Karim']
# Get elements from index 2 to the end
print(names[2:]) # Output: ['Karim', 'Nusrat', 'Habib']
# Get every second element
print(names[::2]) # Output: ['Farjana Akter Mim', 'Karim', 'Habib']
8. Nested Lists
Lists can contain other lists.
Example:
data = [
["Farjana Akter Mim", 21, "Brahmanbaria"],
["Rahim", 25, "Dhaka"],
["Karim", 30, "Chattogram"]
]
# Accessing Nested Elements
print(data[0][0]) # Output: Farjana Akter Mim
print(data[2][2]) # Output: Chattogram
9. Practice Tasks for Day 7
Task 1: Create a List of Your Favorite Movies
Write a program to create and print a list of your top 5 favorite movies.
Task 2: Find the Largest Number in a List
numbers = [5, 12, 8, 21, 7]
print("Largest number:", max(numbers))
Task 3: Reverse a List
Write a program to reverse the order of items in a list without using the reverse()
method.
Task 4: Check for Palindromes
Write a program to check if a list of strings contains any palindromes.
Example:
words = ["radar", "python", "level", "world"]
for word in words:
if word == word[::-1]:
print(f"'{word}' is a palindrome.")
10. Common Mistakes to Avoid
-
Index Out of Range:
Ensure you don’t access indexes beyond the size of the list.names = ["Farjana Akter Mim", "Rahim"] print(names[2]) # Error: Index out of range
-
Mutating the List While Iterating:
Modifying a list while iterating can lead to unexpected behavior. -
Copying by Reference Instead of Value:
Use.copy()
to create a separate copy of a list.
11. Pro Tips for Day 7
- Use list comprehensions for concise and efficient operations.
- Explore built-in functions like
sum()
,min()
, andmax()
for numerical lists. - Practice combining lists with loops for real-world tasks.
🎯 Day 7 Goal:
Practice creating, modifying, and slicing lists. Write at least 5 programs using lists for different operations.
Let me know when you’re ready for Day 8! 🚀