Python - 8

Python - 8: Lists

Lists let you store multiple values inside one variable.

Your challenge: Create a list, access individual items, loop through the list, and add one more item.

✦ Python Editor
▶ Output

Create a list

Lists use square brackets: fruits = ["Apple", "Banana", "Orange"]

Each value inside the list is called an item.

Access list items

Python starts counting list positions at 0.

So fruits[0] gives the first item, while fruits[1] gives the second.

Loop through a list

Use: for fruit in fruits:

The loop runs once for every item in the list.

Add an item

Use: fruits.append("Mango")

This adds the new item to the end of the list.

Try it: Add another fruit and print one of the later items using its index.

Good Python habit: Use plural names such as fruits for lists and a singular name such as fruit for one item inside a loop.

👀 Show Example Solution
fruits = ["Apple", "Banana", "Orange"]

print(fruits[0])
print(fruits[1])

for fruit in fruits:
    print(fruit)

fruits.append("Mango")

print(fruits)

The list stores several strings, indexes access individual items, and append() adds a new item to the end.