Lists#

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:

+----------------------------------------+ |                                        | | cities (list)                          | |                                        | |   +----------+----------+----------+   | |   |          |          |          |   | |   | London   | Paris    | Berlin   |   | |   |          |          |          |   | |   +----------+----------+----------+   | |   |    0 cCFF|    1 cCFF|    2 cCFF|   | |   +----------+----------+----------+   | |   |   -3 cCCF|   -2 cCCF|   -1 cCCF|   | |   +----------+----------+----------+   | |                                        | +----------------------------------------+    /----\               /----\   |cCFF| index number  |cCCF| negative index   \----/               \----/

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.

Example output:

[29, 19, 17, 49, 45, 4]

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 list

  • list.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)

  1. Make a list of words and print it.

  2. Iterate over the list using a for loop and the enumerate function, and delete every other item. Hint: You can check if a number is even with i % 2 == 0

  3. Print the list again.

Example output:

Before: ['Lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur', 'adipiscing', 'elit']
After: ['Lorem', 'dolor', 'sit', 'consectetur', 'adipiscing']

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.

Bonus: Add an optional argument shuffled that defaults to False, which shuffles the deck using the random.shuffle() function.

Ranks

2-9

numeric value

"T"

Ten

"J"

Jack

"Q"

Queen

"K"

King

Suits

"C"

Clubs

"D"

Diamonds

"H"

Hearts

"S"

Spades

Example usage:

>>> deck = make_deck()
>>> len(deck)
52
>>> deck[:13]
['2C', '3C', '4C', '5C', '6C', '7C', '8C', '9C', 'TC', 'JC', 'QC', 'KC', 'AC']

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.

Example output:

>>> deck = make_deck(shuffled=True)
>>> hand = draw(deck, 5)
>>> hand
['KS', '7D', '3H', '2H', '6C']
>>> len(hand)
5
>>> len(deck)
47

Reference#

Lists#

heterogeneous#

Elements in the collection may be of any type.

homogeneous#

All elements in the collection are of the same type.

See also