[concept]Python Basics
Lists & Tuples
# theory
A list is an ordered, mutable collection. Square brackets:
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = ["hello", 42, True, 3.14]
Index from 0. Negative indexes count from the end:
fruits[0] # "apple"
fruits[-1] # "cherry"
fruits[-2] # "banana"
Slice with [start:end:step]. End is exclusive:
numbers = [0, 1, 2, 3, 4, 5]
numbers[1:4] # [1, 2, 3]
numbers[:3] # [0, 1, 2]
numbers[3:] # [3, 4, 5]
numbers[::2] # [0, 2, 4]
Mutating:
fruits.append("date")
fruits.insert(1, "orange")
fruits.remove("banana")
popped = fruits.pop()
Tuples are lists you can't change. Parens. Use them for coordinate-like data or database row tuples:
coordinates = (10, 20)
rgb = (255, 128, 0)
# coordinates[0] = 5 # TypeError
Built-ins that work on both: len(), sum(), min(), max(), sorted().
# examples [3]
# example 01 · list operations
Common operations you'll use constantly
1
2
3
4
5
6
7
8
🐍
# example 02 · slicing examples
Different ways to slice a list
1
2
3
4
5
6
7
🐍
# example 03 · building lists
Adding and modifying list contents
1
2
3
4
5
6
7
8
9
10
11
12
13
14
🐍
# challenges [2]
# challenge 01/02todo
Create a list called 'temps' with values [72, 75, 79, 81, 77]. Print the average temperature.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
🐍
# challenge 02/02todo
Given scores = [88, 92, 75, 95, 87], print the highest and lowest scores, and the range (difference between them).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
🐍
# project
# project-challenge
thread: SF Permits Analysis · reward: 50 xp
# brief
Your city planning dashboard needs a dropdown of all neighborhoods with permits. Extract a list of unique neighborhood names from the permits data.
# task
Extract Unique Neighborhoods
# your code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
🐍