6.1. Creating Lists#

There are several ways to create a new list:

  • Square brackets []: Enclose elements in square brackets (a subscription expression) to create a list literal

  • list() constructor: Convert any iterable (strings, ranges, tuples, etc.) into a list

  • List comprehension: Create lists using a concise expression-based syntax

  • split() method: Convert a string into a list of words or parts

  • Nested lists: Create lists containing other lists as elements

import sys
from pathlib import Path

# Find project root by looking for _config.yml
current = Path.cwd()
for parent in [current, *current.parents]:
    if (parent / '_config.yml').exists():
        project_root = parent
        break
else:
    project_root = Path.cwd().parent.parent

# Add project root to path
sys.path.insert(0, str(project_root))

# Import shared teaching helpers and cell magics
from shared import thinkpython, diagram, jupyturtle, structshape
from shared.download import download

6.1.1. Basic List Creation#

The most common way to create a list is by enclosing comma-separated values in square brackets [].

Syntax:

list_name = [element1, element2, element3, ...]

The elements can be of any type, and you can mix different types in the same list.

### Using square brackets - sequences of items

numbers = [1, 2, 3, 4, 5]               ### a list of integers
fruits = ['apple', 'banana', 'cherry']  ### a list of strings
empty = []                              ### an empty list

print(fruits)
print(numbers)
print(empty)
['apple', 'banana', 'cherry']
[1, 2, 3, 4, 5]
[]
### EXERCISE: Create Different Types of Lists
# Create the following lists:
# 1. A list called 'colors' with three color names
# 2. An empty list called 'empty_list'
# 3. A list called 'mixed' with a string, an integer, and a float
### Your code starts here:



### Your code ends here.

Hide code cell source

# Solution
colors = ['red', 'blue', 'green']
empty_list = []
mixed = ['hello', 42, 3.14]

print(f"Colors: {colors}")
print(f"Empty list: {empty_list}")
print(f"Mixed list: {mixed}")
Colors: ['red', 'blue', 'green']
Empty list: []
Mixed list: ['hello', 42, 3.14]

6.1.2. list() Constructor#

The list() constructor converts any iterable (strings, ranges, tuples, etc.) into a list. This is useful when you need to convert data from one sequence type to another.

chars = list('spam')            ### a list of characters
nums = list(range(5))           ### a list of numbers from 0 to 4
tuple_data = (1, 2, 3)
list_data = list(tuple_data)    ### a list created from a tuple

print(chars)
print(nums)
print(list_data)
['s', 'p', 'a', 'm']
[0, 1, 2, 3, 4]
[1, 2, 3]
### EXERCISE: Convert Using list() Constructor
# 1. Convert the string "Python" into a list of characters
# 2. Create a list of numbers from 10 to 14 using range() and list()
### Your code starts here:



### Your code ends here.

Hide code cell source

# Solution
chars = list('Python')
numbers = list(range(10, 15))

print(f"Characters: {chars}")
print(f"Numbers: {numbers}")
Characters: ['P', 'y', 't', 'h', 'o', 'n']
Numbers: [10, 11, 12, 13, 14]

6.1.3. List Comprehension#

List comprehension provides a concise way to create lists based on existing sequences or ranges. It’s a powerful and Pythonic approach that often replaces traditional loops. They’re a more Pythonic alternative to using for loops to build lists.

Basic Syntax:

[expression for item in iterable]

With Condition:

[expression for item in iterable if condition]
# Traditional way
squares = []
for x in range(5):
    squares.append(x**2)
print("Traditional:", squares)

# List comprehension way
squares = [x**2 for x in range(5)]
print("Comprehension:", squares)

# With condition
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print("Even squares:", even_squares)
Traditional: [0, 1, 4, 9, 16]
Comprehension: [0, 1, 4, 9, 16]
Even squares: [0, 4, 16, 36, 64]
# More complex list comprehensions
words = ['hello', 'world', 'python', 'programming']

# Get lengths of words
lengths = [len(word) for word in words]
print("Word lengths:", lengths)

# Get uppercase words longer than 5 characters
long_words = [word.upper() for word in words if len(word) > 5]
print("Long words:", long_words)

# Nested comprehension - flatten a 2D list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [item for row in matrix for item in row]
print("Flattened:", flattened)
Word lengths: [5, 5, 6, 11]
Long words: ['PYTHON', 'PROGRAMMING']
Flattened: [1, 2, 3, 4, 5, 6, 7, 8, 9]
### EXERCISE: convert string to uppercase using list comprehension
### Hint: use str.upper() method
### Your code starts here:



### Your code ends here.

Hide code cell source

# Convert strings to uppercase
words = ['hello', 'world', 'python']
uppercase_words = [word.upper() for word in words]
print(uppercase_words)
['HELLO', 'WORLD', 'PYTHON']
### EXERCISE: Filter list using list comprehension: 
### Create a new list with only words longer than 5 characters 
### Hint: use len() function
### Your code starts here:
words = ['apple', 'banana', 'cherry', 'date', 'elderberry']



### Your code ends here.

Hide code cell source

words = ['apple', 'banana', 'cherry', 'date', 'elderberry']
long_words = [word for word in words if len(word) > 5]
print(long_words)
['banana', 'cherry', 'elderberry']
### EXERCISE: List Comprehension Practice
# 1. Create a list of cubes (x^3) for numbers 1 through 5
# 2. Create a list of only odd numbers from 1 to 20
### Your code starts here:



### Your code ends here.

Hide code cell source

# Solution
cubes = [x**3 for x in range(1, 6)]
odds = [x for x in range(1, 21) if x % 2 != 0]

print(f"Cubes: {cubes}")
print(f"Odd numbers: {odds}")
Cubes: [1, 8, 27, 64, 125]
Odd numbers: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

6.1.4. Lists and Strings#

This section explores common patterns for working with strings and lists, focusing on converting between them and manipulating them together.

A string is a sequence of characters and a list is a sequence of values, but a list of characters is not the same as a string. To convert a string to a list of individual characters, use the list() function (covered earlier). To break a string into words or parts, use the split() method shown below.

6.1.4.1. split() Method#

The split() method breaks a string into a list of words or parts based on a delimiter. By default, it splits on whitespace.

# Split by whitespace (default)
words = 'hello world python'.split()
print(words)

# Split by custom delimiter
data = 'apple,banana,cherry'.split(',')
print(data)
['hello', 'world', 'python']
['apple', 'banana', 'cherry']

You can also use an optional delimiter argument to specify which characters to use as word boundaries:

s = 'ex-parrot'
t = s.split('-')
print(t)  # ['ex', 'parrot']
['ex', 'parrot']

6.1.4.2. join() Method#

If you have a list of strings, you can concatenate them into a single string using join(). Note that join() is a string method, so you invoke it on the delimiter and pass the list as an argument.

delimiter = ' '
t = ['pining', 'for', 'the', 'fjords']
s = delimiter.join(t)
s
'pining for the fjords'

In this case the delimiter is a space character, so join puts a space between words. To join strings without spaces, you can use the empty string, '', as a delimiter.

### EXERCISE: Using split() and join()
# 1. Split the sentence "Python is an amazing language" into a list of words
# 2. Split the string "2026-02-16" by the delimiter "-"
# 3. Take the sentence "Python programming is fun", 
#    split it, 
#    reverse the list, and 
#    join back with " - "
### Your code starts here:



### Your code ends here.

Hide code cell source

# Solution
# 1. Split sentence into words
sentence = "Python is an amazing language"
words = sentence.split()

# 2. Split date string by delimiter
date_string = "2026-02-16"
date_parts = date_string.split("-")

# 3. Split, reverse, and join
sentence2 = "Python programming is fun"
words2 = sentence2.split()
words2.reverse()
result = " - ".join(words2)

print(f"1. Words: {words}")
print(f"2. Date parts: {date_parts}")
print(f"3. Reversed and joined: {result}")
1. Words: ['Python', 'is', 'an', 'amazing', 'language']
2. Date parts: ['2026', '02', '16']
3. Reversed and joined: fun - is - programming - Python

6.1.5. Nested Lists#

  • Although a list can contain another list, the nested list still counts as a single element.

  • The elements of a list don’t have to be the same data type.

The following lists contain a string, a float, an integer, and another list (nested). We see that the length of the list mixed_list is 4, although it looks having more than 4 elements, but the 4th element is a list and counted only as 1 element.

numbers = [1, 2, 3, 4, 5]
mixed_list = ['spam', 2.0, 5, numbers ]

print(mixed_list)
print(f"There are {len(mixed_list)} elements in the mixed list.")
['spam', 2.0, 5, [1, 2, 3, 4, 5]]
There are 4 elements in the mixed list.
nested_list = [ 
               [1, 2], 
               [3, 4], 
               [5, 6]
               ]
print(nested_list)
print(f"The nested list has {len(nested_list)} elements and they are lists themselves.")
[[1, 2], [3, 4], [5, 6]]
The nested list has 3 elements and they are lists themselves.
### EXERCISE: Working with Nested Lists
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# 1. Access the second row (index 1)
# 2. Access the element in the first row, third column (value should be 3)
# 3. Calculate the total number of elements (not rows) using len()
### Your code starts here:



### Your code ends here.

Hide code cell source

# Solution
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
second_row = matrix[1]
element_1_3 = matrix[0][2]
total_elements = len(matrix) * len(matrix[0])  # rows * cols

print(f"Second row: {second_row}")
print(f"Element at [0][2]: {element_1_3}")
print(f"Total elements: {total_elements}")
Second row: [4, 5, 6]
Element at [0][2]: 3
Total elements: 9