Lists in Python

Lists are one of the most commonly used data structures in Python. They allow you to store multiple values in a single variable and organize your data in a sequential manner. You can think of a list as a container that holds items, which can be of any data type.

Creating a List

You can create a list using square brackets [] and separating the items with commas. Here’s an example:

my_list = [1, 2, 3, 4, 5]

Accessing Items in a List

Each item in a list has an index number, starting from 0. You can access individual items using their index:

print(my_list[0])  # Outputs: 1
print(my_list[3])  # Outputs: 4

Modifying a List

Lists are mutable, which means you can change the items inside them. You can add, remove, or modify items:

my_list[2] = 10  # Changing the third item to 10
my_list.append(6)  # Adding a new item to the end of the list
my_list.remove(1)  # Removing the item with the value 1

Looping Through a List

One common use of lists is iterating over them with loops:

for item in my_list:
    print(item)

Exercise

Create a list of your favorite fruits. Use a loop to print each fruit from the list, then add a new fruit to the list and print the updated list.