fruits = ["apple", "banana", "cherry"]
print(fruits)['apple', 'banana', 'cherry']
A list stores a collection of items in a single variable. Lists are useful when the number of items may change, such as a playlist, a shopping basket, or a class roster.
Create a list by placing comma-separated items inside square brackets [].
fruits = ["apple", "banana", "cherry"]
print(fruits)['apple', 'banana', 'cherry']
print(type(fruits))<class 'list'>
A list can contain any type of data. It can also mix types, although lists are often easier to work with when their items represent the same kind of information.
profile = ["Maya", 21, True]
print(profile)['Maya', 21, True]
A list can contain other lists. This is called a nested list.
weekly_schedule = [
["Python", "Design"],
["Economics", "Writing"],
["Statistics", "Python"],
]
print(weekly_schedule)[['Python', 'Design'], ['Economics', 'Writing'], ['Statistics', 'Python']]
Items remain in a specific order. Python uses zero-based indexing, so the first item is at index 0.
fruits = ["apple", "banana", "cherry", "pineapple", "watermelon"]
print(fruits[0])apple
Indexing lists works exactly like strings, which are also ordered sequences.
print(fruits[1])banana
Negative indexes count from the end. The index -1 refers to the last item.
print(fruits[-1])watermelon
Slicing selects part of a list. The starting index is included and the ending index is excluded.
print(fruits[1:4])['banana', 'cherry', 'pineapple']
print(fruits[:2])['apple', 'banana']
print(fruits[3:])['pineapple', 'watermelon']
Use more than one index to access an item inside a nested list.
weekly_schedule = [
["Python", "Design"],
["Economics", "Writing"],
["Statistics", "Python"],
]
print(weekly_schedule[1])['Economics', 'Writing']
print(weekly_schedule[1][0])Economics
Without running the code, write the three lines that it prints.
shows = ["Severance", "The Bear", "Andor", "Arcane"]
print(shows[0])
print(shows[-2])
print(shows[1:3])Severance
Andor
['The Bear', 'Andor']
Lists are mutable, which means their contents can change after creation.
fruits = ["apple", "banana", "cherry"]
fruits[0] = "orange"
print(fruits)['orange', 'banana', 'cherry']
Lists can contain the same value more than once.
votes = ["blue", "green", "blue", "red", "blue"]
print(votes)['blue', 'green', 'blue', 'red', 'blue']
Lists are sequences, like strings. The + operator joins two lists.
morning_tasks = ["check email", "attend class"]
afternoon_tasks = ["study", "go to the gym"]
all_tasks = morning_tasks + afternoon_tasks
print(all_tasks)['check email', 'attend class', 'study', 'go to the gym']
Both operands must be lists. A single item must be placed inside a list before it can be concatenated.
tasks = ["check email", "attend class"]
tasks = tasks + "study"TypeError: can only concatenate list (not "str") to list
tasks = ["check email", "attend class"]
tasks = tasks + ["study"]
print(tasks)['check email', 'attend class', 'study']
Multiplying a list repeats its items.
notification_pattern = ["work", "break"] * 3
print(notification_pattern)['work', 'break', 'work', 'break', 'work', 'break']
The len() function returns the number of items in a list.
fruits = ["apple", "banana", "cherry", "pineapple", "watermelon"]
print(len(fruits))5
For a nested list, len() counts only the items in the outer list.
weekly_schedule = [
["Python", "Design"],
["Economics", "Writing"],
["Statistics", "Python"],
]
print(len(weekly_schedule))
print(len(weekly_schedule[0]))3
2
The list below stores two conference days. Write code that prints:
schedule = [
["Opening", "Data Ethics", "Networking"],
["Python Lab", "Career Panel", "Closing"],
]print(len(schedule))
print(len(schedule[1]))
print(schedule[1][0])Most list methods modify the original list in place. They do not usually need to be assigned back to the variable.
append() adds one item to the end of a list.
playlist = ["Intro", "Night Drive"]
playlist.append("Last Train")
print(playlist)['Intro', 'Night Drive', 'Last Train']
extend() adds every item from another iterable.
playlist = ["Intro", "Night Drive"]
new_tracks = ["Last Train", "Home"]
playlist.extend(new_tracks)
print(playlist)['Intro', 'Night Drive', 'Last Train', 'Home']
insert() adds an item at a specified index.
playlist.insert(1, "Interlude")
print(playlist)['Intro', 'Interlude', 'Night Drive', 'Last Train', 'Home']
append(["A", "B"]) adds one nested list. extend(["A", "B"]) adds two separate items.
Start with the list below and use list methods to make these changes:
"Arrival" to the end."Spirited Away" at the beginning."Moonlight" and "Dune" in one operation.watchlist = ["Past Lives", "The Matrix"]watchlist = ["Past Lives", "The Matrix"]
watchlist.append("Arrival")
watchlist.insert(0, "Spirited Away")
watchlist.extend(["Moonlight", "Dune"])
print(watchlist)remove() removes the first occurrence of a value.
guests = ["Ava", "Leo", "Nora", "Leo"]
guests.remove("Leo")
print(guests)['Ava', 'Nora', 'Leo']
pop() removes and returns an item. With no index, it removes the last item.
guests = ["Ava", "Leo", "Nora", "Sam"]
cancelled_guest = guests.pop(1)
print(cancelled_guest)
print(guests)Leo
['Ava', 'Nora', 'Sam']
clear() removes all items.
guests.clear()
print(guests)[]
index() returns the index of the first matching item. count() returns how many times a value appears.
responses = ["yes", "no", "yes", "maybe", "yes"]
print(responses.index("maybe"))
print(responses.count("yes"))3
3
sort() sorts the original list. reverse() reverses its current order.
cities = ["Tokyo", "Lima", "Berlin", "Accra"]
cities.sort()
print(cities)
cities.reverse()
print(cities)['Accra', 'Berlin', 'Lima', 'Tokyo']
['Tokyo', 'Lima', 'Berlin', 'Accra']
The key argument lets us choose what Python uses for sorting.
def last_character(word):
return word[-1]
animals = ["Dog", "Cat", "Bird", "Horse"]
animals.sort(key=last_character)
print(animals)['Bird', 'Horse', 'Dog', 'Cat']
Sort the podcast titles from shortest to longest. Use len as the sorting key.
podcasts = ["Radiolab", "Today Explained", "Serial", "99% Invisible"]podcasts = ["Radiolab", "Today Explained", "Serial", "99% Invisible"]
podcasts.sort(key=len)
print(podcasts)The programmer wants to add two destinations separately, but the result is not correct. Fix one line.
destinations = ["Lisbon", "Seoul"]
destinations.append(["Cairo", "Oslo"])
print(destinations)Use extend() so that both destinations become individual items.
destinations = ["Lisbon", "Seoul"]
destinations.extend(["Cairo", "Oslo"])
print(destinations)Complete a small reading tracker that:
finished_book.reading_list = ["Beloved", "Dune", "The Hobbit"]
reading_list.append("Pachinko")
finished_book = reading_list.pop(1)
reading_list.sort()
print(f"Finished: {finished_book}")
print(f"Still to read: {reading_list}")
print(f"Books remaining: {len(reading_list)}")[].append(), remove(), and sort() modify a list in place.