🔹 1. What is a List?
A list is a sequence of values (items). They are ordered, changeable (mutable), and allow duplicate members. Defined by square brackets
[].Example:
my_list = ["apple", 3.14, True, 100]
print(my_list)
Output:
['apple', 3.14, True, 100]🔹 2. Accessing List Items
Items are accessed by their index, which starts at
0 for the first item.Example:
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # First item
print(fruits[2]) # Third item
print(fruits[-1]) # Last item
Output:
applecherrycherry🔹 3. Modifying List Items
You can change an item by referring to its index.
Example:
colors = ["red", "green", "blue"]
colors[1] = "yellow" # Change 'green' to 'yellow'
print(colors)
Output:
['red', 'yellow', 'blue']🔹 4. Adding Items to a List
•
.append(): Adds an item to the end of the list.•
.insert(index, item): Adds an item at a specific index.Example:
names = ["Alice", "Bob"]
names.append("Charlie") # Add to end
names.insert(0, "David") # Add at the beginning
print(names)
Output:
['David', 'Alice', 'Bob', 'Charlie']🔹 5. Removing Items from a List
•
.remove(item): Removes the first occurrence of a specified item.•
.pop(index): Removes (and returns) the item at a specified index (or the last item if no index is given).•
del list[index]: Deletes the item at a specific index.Example:
numbers = [10, 20, 30, 20, 40]
numbers.remove(20) # Removes first '20'
del numbers[0] # Removes '10'
print(numbers)
Output:
[30, 20, 40]🎯 Today's Goal(What you should do)
✔️ Understand what lists are and how to create them
✔️ Access items using indexing
✔️ Modify, add, and remove items from lists