Skip to main content

Lists

Storing Multiple Values in Python

· 3 min read

In the previous unit, we explored string operations. Now let's look at lists, Python's way of storing multiple values in a single variable.

Lists

What Is a List?

A list is a collection of items that are ordered and changeable. Lists allow duplicate values. You create them with square brackets, separating items with commas.

fruits = ["apple", "banana", "cherry"]
print(fruits) # Outputs: ['apple', 'banana', 'cherry']

Lists can hold different types together:

my_list = [1, "Hello", True]

This list contains an integer, a string, and a boolean.

Accessing Items

You access list items by their index. Python indexing starts at 0, so the first item is at index 0.

fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Outputs: apple
print(fruits[1]) # Outputs: banana
print(fruits[2]) # Outputs: cherry

Modifying Lists

Lists are mutable, meaning you can change their contents after creation. Assign a new value to a specific index:

fruits = ["apple", "banana", "cherry"]
fruits[1] = "orange"
print(fruits) # Outputs: ['apple', 'orange', 'cherry']

List Methods

Python provides methods for common list operations.

numbers = [3, 1, 4, 1, 5, 9]

numbers.append(2)
print(numbers) # Outputs: [3, 1, 4, 1, 5, 9, 2]

numbers.remove(1)
print(numbers) # Outputs: [3, 4, 1, 5, 9, 2]

numbers.sort()
print(numbers) # Outputs: [1, 2, 3, 4, 5, 9]

numbers.reverse()
print(numbers) # Outputs: [9, 5, 4, 3, 2, 1]

append() adds an item to the end. remove() deletes the first occurrence of a value. sort() arranges items in ascending order. reverse() flips the order.

Project: Drawing Shapes from a List

Let's store shape definitions in a list and have Turtle draw each one. Each number represents how many sides a shape has.

import turtle

screen = turtle.Screen()
screen.setup(width=800, height=600)
screen.bgcolor("white")

t = turtle.Turtle()

def draw_shape(turtle, side_length, num_sides):
angle = 360 / num_sides
for _ in range(num_sides):
turtle.forward(side_length)
turtle.right(angle)

# List of shapes: triangle, square, pentagon, hexagon, octagon
shapes = [3, 4, 5, 6, 8]

t.penup()
t.goto(-350, 0)
t.pendown()

for shape in shapes:
draw_shape(t, 50, shape)
t.penup()
t.forward(140)
t.pendown()

t.hideturtle()
turtle.done()

The shapes list holds the number of sides for each shape. The loop iterates through the list, drawing a triangle (3 sides), then a square (4), pentagon (5), hexagon (6), and octagon (8). This shows how lists let you store data and process it systematically.

Try modifying the list to draw different shapes, or add a second list for colors and apply a different color to each shape.

In the next unit, we'll explore list comprehensions, a concise way to generate lists in Python.