Lists
Contents
Lists#
An ordered collection of arbitrary objects accessed via index numbers.
- Type
list- Synatx
[item,...]- Bases
Sequence, Iterable
- State
Mutable
- Position
Ordered
- Composition
Heterogeneous
- Diversity
Repeatable
- Access
Subscriptable
- Value
Not hashable
Part 1: Basics#
Part 1.1 Creating#
There are several ways to create a new list. The simplest is to enclose the
elements, separated by commas, in square brackets ([ and ]):
cities = ["London", "Paris", "Berlin"]
Each element is assigned a successive index number, starting at 0.
Under the hood, the cities list looks like this:
Part 1.2: Accessing#
Items are accessed via subscription, using [ ] after the object
to enclose a selector expression. For example, use the index number to select
an individual item.
print(cities[0])
London
You can use a negative index number to access elements starting at the end.
Negative index numbers are shorthand for
length of list + negative index value.
print(cities[-1])
Berlin
Subscription is also used to change list elements.
cities[1] = "Amsterdam"
print(cities)
['London', 'Amsterdam', 'Berlin']
Part 1.3: Adding#
To add an element to the end of a list, use the .append() method.
cities.append("Dublin")
print(cities)
['London', 'Amsterdam', 'Berlin', 'Dublin']
Or you can add an item at a specific position with the .insert() method.
cities.insert(1, "Italy")
print(cities)
['London', 'Italy', 'Amsterdam', 'Berlin', 'Dublin']
Or you can add all the items from another iterable with the .extend()
method.
cities.extend(["San Francisco", "Brooklyn", "Denver"])
print(cities)
['London', 'Italy', 'Amsterdam', 'Berlin', 'Dublin', 'San Francisco', 'Brooklyn', 'Denver']
Part 1.4: Removing#
Use the del keyword to remove an element by index.
del cities[1]
print(cities)
['London', 'Amsterdam', 'Berlin', 'Dublin', 'San Francisco', 'Brooklyn', 'Denver']
Or to remove an element by value, use the .remove() method.
cities.remove("London")
print(cities)
['Amsterdam', 'Berlin', 'Dublin', 'San Francisco', 'Brooklyn', 'Denver']
Part 1.5: Membership#
Check if list contains value using the in operator:
"London" in cities
False
Check if list does not contains value using the not in operator:
"London" not in cities
True
To look up the index number of a particular value, use the .index() method.
Get the first index number of value:
cities.index("Dublin")
2
Part 1.6: Exercises#
Exercise 46 (Random Lotto Numbers)
Generate a list of six unique numbers between 1 and 49, then print the list.
Need help?
import the
randommodulemake an empty list assigned to the variable
numbersstart a
whileloop with the condition that the length ofnumbersis less than6in the loop:
get a random number between
1and49using therandom.randint()method and assign it to the variablenumcheck if
numis in thenumberslistif not, append
numtonumbers
print the
numberslist
Example output:
[29, 19, 17, 49, 45, 4]
Solution to Exercise 46 (Random Lotto Numbers)
1import random
2
3numbers = []
4while len(numbers) < 6:
5 num = random.randint(1, 49)
6 if num not in numbers:
7 numbers.append(num)
8
9print(numbers)
Part 2: Slices#
You often want to extract part of a list. This could be accomplished using a
for loop, for example:
partial, start, stop = [], 2, 5
for i, item in enumerate(cities):
if i >= start and i < stop:
partial.append(item)
print(partial)
['Dublin', 'San Francisco', 'Brooklyn']
Python provides handy dandy slice functionality, which is also supported by subscription.
The syntax is: COLLECTION[START:STOP]
Using this feature we can extract the same part of the list like so:
cities[2:5]
['Dublin', 'San Francisco', 'Brooklyn']
A missing STOP value will default to the end of the list.
cities[2:]
['Dublin', 'San Francisco', 'Brooklyn', 'Denver']
A missing START value will default to the beginning of the list.
cities[:2]
['Amsterdam', 'Berlin']
If both are missing, the slice will be a copy of the whole list.
cities[:]
['Amsterdam', 'Berlin', 'Dublin', 'San Francisco', 'Brooklyn', 'Denver']
Part 3: Values#
The list type is heterogeneous, which means it can contain arbitrary
objects of any type. So far in this lesson our example list has contained all
str objects. But in fact, we can mix and match.
[None, True, 'two', 3.0, 4]
[None, True, 'two', 3.0, 4]
We can use multiple assignment to easily assign assign all of the values in a list to a series of variables.
book = [5, "Hitchhiker's Guide to the Galaxy", "Douglas Adams", 1979]
rating, title, author, year = book
print(f"{title} ({year}) by {author}: {rating} stars")
Hitchhiker's Guide to the Galaxy (1979) by Douglas Adams: 5 stars
Lists can also contain other lists.
meals = [
["omelet", "turkey wrap", "tacos"],
["oatmeal", "turkey burger", "tamales"],
["yogurt", "chicken salad", "enchiladas"],
]
You can access items in the nested lists by using multiple indexing operations.
print(f"Dinner tonight is: {meals[0][2]}.")
print(f"Tomorrow for breakfast we're having: {meals[1][0]}.")
Dinner tonight is: tacos.
Tomorrow for breakfast we're having: oatmeal.
Part 4: Iteration#
Iterate over each element using a for loop.
for item in cities:
print(item)
Amsterdam
Berlin
Dublin
San Francisco
Brooklyn
Denver
To include the index number, use the enumerate() function.
for i, item in enumerate(cities):
print(i, item)
0 Amsterdam
1 Berlin
2 Dublin
3 San Francisco
4 Brooklyn
5 Denver
To iterate over a nested list, you’ll need nested for loops. The VAR in the
first loop will point to the child list; the nested VAR will point to the
child list elements.
table = [
[1, 2, 3, 4],
[2, 4, 6, 8],
[3, 6, 9, 12],
[4, 8, 12, 16],
]
# iterate over the table list and assign each child list to row
for row in table:
# iterate over the child list and assign each element to product
for product in row:
# print the number, right aligned, followed by two spaces
print(str(product).rjust(2), end=" ")
# print a new line at the end of every row
print()
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
If you are certain to have the same number of items in every row, you can use
multiple assignment in the for loop VAR.
for breakfast, lunch, dinner in meals:
print(f"Breakfast: {breakfast}")
print(f"Lunch: {lunch}")
print(f"Dinner: {dinner}")
print()
Breakfast: omelet
Lunch: turkey wrap
Dinner: tacos
Breakfast: oatmeal
Lunch: turkey burger
Dinner: tamales
Breakfast: yogurt
Lunch: chicken salad
Dinner: enchiladas
You can even combine this technique with enumerate() elements by enclosing
the child element variable names in ( ).
for i, (breakfast, lunch, dinner) in enumerate(meals):
if i == 0:
day = "Today"
elif i == 1:
day = "Tomorrow"
else:
day = f"In {i} days"
print(f"### {day}\n")
print(f"Breakfast: {breakfast}")
print(f"Lunch: {lunch}")
print(f"Dinner: {dinner}")
print()
### Today
Breakfast: omelet
Lunch: turkey wrap
Dinner: tacos
### Tomorrow
Breakfast: oatmeal
Lunch: turkey burger
Dinner: tamales
### In 2 days
Breakfast: yogurt
Lunch: chicken salad
Dinner: enchiladas
Part 5: Sorting#
There are two ways to sort a list
sorted(list)– returns a new sorted listlist.sort()– sorts the list in place
To demonstrate this, we’ll use the FRUIT list.
# define global FRUIT list
FRUIT = ["cherry", "apple", "date", "bananna", "elderberry"]
We’ll make copies and sort using both methods side by side.
Returned sorting
# make a fresh copy of FRUIT
fruit = FRUIT[:]
pprint(fruit)
['cherry',
'apple',
'date',
'bananna',
'elderberry']
# sorted() returns a new list
result = sorted(fruit)
pprint(result)
['apple',
'bananna',
'cherry',
'date',
'elderberry']
# and leaves fruit alone
pprint(fruit)
['cherry',
'apple',
'date',
'bananna',
'elderberry']
In-place sorting
# make a fresh copy of FRUIT
fruit = FRUIT[:]
pprint(fruit)
['cherry',
'apple',
'date',
'bananna',
'elderberry']
# .sort() returns None
result = fruit.sort()
pprint(result)
-
None
# but fruit was modified in place
pprint(fruit)
['apple',
'bananna',
'cherry',
'date',
'elderberry']
Part 6: Exercises#
Exercise 47 (Delete Alternate Items)
Make a list of words and print it.
Iterate over the list using a
forloop and theenumeratefunction, and delete every other item. Hint: You can check if a number is even withi % 2 == 0Print the list again.
Example output:
Before: ['Lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur', 'adipiscing', 'elit']
After: ['Lorem', 'dolor', 'sit', 'consectetur', 'adipiscing']
Solution to Exercise 47 (Delete Alternate Items)
1words = ["Lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit"]
2print("Before:", words)
3for i, elm in enumerate(words):
4 if i % 2 != 0:
5 del words[i]
6print("After:", words)
Exercise 48 (Deck of Cards)
Write a function make_deck() to generate a list of 52 playing cards where
each card is a number or letter representing the rank, and a letter or number
representing the suit.
Need help?
make a list of
SUITSthat contains the suit lettersmake a list of
RANKSincluding the rankswrite a function
make_deck()in the function:make an empty
decklistuse a
forloop to iterate over eachSUITwith the variable namesuituse a (nested)
forloop to iterate over eachRANKwith the variable namerankcombine the
rankandsuitinto one string and assign it to the variablecardappend
cardto thedecklist
return
deck
Bonus: Add an optional argument shuffled that defaults to False, which
shuffles the deck using the random.shuffle() function.
Ranks
|
numeric value |
|
Ten |
|
Jack |
|
Queen |
|
King |
Suits
|
Clubs |
|
Diamonds |
|
Hearts |
|
Spades |
Example usage:
>>> deck = make_deck()
>>> len(deck)
52
>>> deck[:13]
['2C', '3C', '4C', '5C', '6C', '7C', '8C', '9C', 'TC', 'JC', 'QC', 'KC', 'AC']
Solution to Exercise 48 (Deck of Cards)
1from random import shuffle
2
3SUITS = ["C", "D", "H", "S"]
4RANKS = list(range(2, 10))
5RANKS.extend(["T", "J", "Q", "K", "A"])
6
7def make_deck(shuffled=False):
8 """Return a deck of 52 playing cards, a list where each element is a string
9 of two characters, the first character representing the rank, and the
10 second representing the suit.
11 The suit letters are C, D, H, and S.
12 The rank letters are T, J, Q, K and A.
13
14 >>> deck = make_deck()
15 >>> len(deck)
16 52
17 >>> deck[:13]
18 ['2C', '3C', '4C', '5C', '6C', '7C', '8C', '9C', 'TC', 'JC', 'QC', 'KC', 'AC']
19 """
20 deck = []
21 for suit in SUITS:
22 for rank in RANKS:
23 card = f"{rank}{suit}"
24 deck.append(card)
25
26 if shuffled:
27 shuffle(deck)
28
29 return deck
Exercise 49 (Hand of Cards Exercise)
Write a draw() function that takes two arguments, a deck containing a deck
of cards from the make_deck() function, and a size with the number of cards
to draw. It should return a new list of cards, with e a length of size, that
have been removed from the deck.
Need help?
Write a
draw()function that takes two arguments:deckandsizemake an empty list assigned to the variable
cardsuse a
forloop to iterate over arange()iterable up tosizeif there are no cards left in the deck,
breakget one card from the deck using the
.pop()method and assign it to the variablecardappend
cardto thecardslist
return the
cardslist
Example output:
>>> deck = make_deck(shuffled=True)
>>> hand = draw(deck, 5)
>>> hand
['KS', '7D', '3H', '2H', '6C']
>>> len(hand)
5
>>> len(deck)
47
Solution to Exercise 49 (Hand of Cards Exercise)
1def draw(deck, size=5):
2 """Return a list of cards removed from deck
3
4 >>> deck = make_deck(shuffled=True)
5 >>> hand = draw(deck)
6 >>> len(hand)
7 5
8 >>> len(hand[0])
9 2
10 >>> len(deck)
11 47
12 >>> hand[0] in deck
13 False
14 """
15 cards = []
16 for i in range(size):
17 if not deck:
18 break
19 card = deck.pop()
20 cards.append(card)
21
22 return cards
23
Reference#
Lists#
See also