Lesson 19 of 4048%
(Progress persistence is disabled until Phase 9)
Python
Beginner
Lists
Store multiple items in a single variable.
Lists
What You’ll Learn
You’ll learn how to create and access items in a list, one of Python’s most versatile data structures.
What is a List?
Lists are used to store multiple items in a single variable. Lists are created using square brackets [].
fruits = ["apple", "banana", "cherry"]
print(fruits)
Accessing Items
List items are ordered and indexed. The first item has index 0, the second item has index 1, etc.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[1]) # banana
Negative Indexing
Negative indexing means starting from the end. -1 refers to the last item, -2 refers to the second to last item, etc.
fruits = ["apple", "banana", "cherry"]
print(fruits[-1]) # cherry
Changing Item Values
Lists are mutable, meaning you can change, add, and remove items after the list has been created.
fruits = ["apple", "banana", "cherry"]
fruits[1] = "mango"
print(fruits) # ["apple", "mango", "cherry"]