Skip to content

Data Structures

>Data Structures — cheat sheet

Choose the right collection to organize values, text, and named information in your programs.

Lists

colors = ["red", "green", "blue"]
Lists keep ordered values in square brackets.
print(colors[0], colors[-1])
Index 0 is first; index -1 is last.
colors.append("purple")
colors.insert(1, "yellow")
Add one item at the end or at an index.
colors.remove("green")
last_color = colors.pop()
Remove a matching item or remove and return the last one.

List order and copies

ordered = sorted([8, 3, 5])
sorted returns a new sorted list.
scores = [8, 3, 5]
scores.sort()
sort changes the existing list.
scores.reverse()
reverse changes the existing list order.
copy_scores = scores.copy()
copy makes a separate shallow list.

Tuples and strings

point = (3, 5)
print(point[1])
Tuples are ordered values that cannot be changed.
one_item = ("hello",)
A one-item tuple needs a trailing comma.
name, age = ("Mina", 14)
Unpack tuple values into separate names.
clean = "  Hello  ".strip().lower()
String methods return new text because strings are immutable.

Working with strings

print("Python"[1:4])
Slice text from a start index up to, not including, an end index.
words = "red,blue".split(",")
split turns text into a list of strings.
label = " | ".join(["red", "blue"])
join combines strings with a chosen separator.
print("banana".find("na"))
find returns the first position or -1.

Sets, dictionaries, and comprehensions

colors = {"red", "blue", "red"}
colors.add("green")
Sets keep unique values and support add.
print({1, 2, 3} & {3, 4})
& finds values shared by two sets.
student = {"name": "Ivy"}
print(student.get("level", "beginner"))
get returns a fallback for a missing dictionary key.
squares = [number * number for number in [1, 2, 3]]
A list comprehension transforms every item concisely.
All cheat sheets