AiTechWorlds
AiTechWorlds
Picture this: You're heading to the grocery store. You grab a pen and scribble on a piece of paper — milk, eggs, bread, apples, cheese. As you walk through the aisles, you cross items off. Near the checkout, you remember you need butter, so you add it at the bottom.
That piece of paper is a list. It holds multiple items, in order, and you can add to it, remove from it, and check what's in it at any time.
Python lists work exactly the same way — except they live in your computer's memory instead of your pocket.
Why does this matter? Without lists, every piece of related data needs its own variable. Imagine writing
score1 = 85,score2 = 92,score3 = 78... for 30 students. Lists let you group related data together under one name and work with it efficiently.
A list is a Python data structure that stores multiple items in a single variable, in a specific order. Lists are:
# An empty list
shopping = []
# A list with items
fruits = ["apple", "banana", "cherry"]
# A list of numbers
scores = [85, 92, 78, 95, 88]
# A mixed list
person = ["Alice", 25, True, 5.6]
Line by line:
[] — square brackets define a listEvery item in a list has an index — a position number. Python starts counting at 0, not 1. This trips up beginners, but you'll quickly get used to it.
Think of it like apartment numbers in a building where the ground floor is floor 0.
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
print(fruits[0]) # apple
print(fruits[2]) # cherry
print(fruits[-1]) # elderberry (last item)
print(fruits[-2]) # date (second to last)
| Item | Positive Index | Negative Index |
|---|---|---|
"apple" | 0 | -5 |
"banana" | 1 | -4 |
"cherry" | 2 | -3 |
"date" | 3 | -2 |
"elderberry" | 4 | -1 |
Tip: Negative indexing counts from the end.
-1is always the last item, which is handy when you don't know how long the list is.
cart = ["bread", "milk"]
# append() — adds to the END
cart.append("eggs")
print(cart) # ['bread', 'milk', 'eggs']
# insert(position, item) — adds at a specific position
cart.insert(1, "butter")
print(cart) # ['bread', 'butter', 'milk', 'eggs']
append(item) — always adds to the end. Fast and simple.
insert(index, item) — inserts before the given index position.
cart = ["bread", "butter", "milk", "eggs", "milk"]
# remove() — removes FIRST occurrence of a value
cart.remove("milk")
print(cart) # ['bread', 'butter', 'eggs', 'milk']
# pop() — removes by index (default: last item), RETURNS the removed item
removed = cart.pop()
print(removed) # 'milk'
print(cart) # ['bread', 'butter', 'eggs']
# pop with index
removed = cart.pop(0)
print(removed) # 'bread'
print(cart) # ['butter', 'eggs']
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print(len(numbers)) # 8 — count of items
print(sum(numbers)) # 31 — total of all numbers
print(max(numbers)) # 9 — largest item
print(min(numbers)) # 1 — smallest item
scores = [85, 42, 93, 67, 78]
scores.sort() # sorts in-place, ascending
print(scores) # [42, 67, 78, 85, 93]
scores.sort(reverse=True) # sorts descending
print(scores) # [93, 85, 78, 67, 42]
scores.reverse() # flips the order in-place
print(scores) # [42, 67, 78, 85, 93]
Important:
.sort()and.reverse()modify the original list. They do not return a new one.
incolors = ["red", "green", "blue"]
print("red" in colors) # True
print("yellow" in colors) # False
print("green" not in colors) # False
This is the Python way of asking: "Is this item somewhere in my list?"
Slicing lets you extract a sub-list from a list. The syntax is:
list[start:end:step]
start — index to begin (included)end — index to stop (NOT included)step — how many to skip (optional, default is 1)months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
print(months[0:3]) # ['Jan', 'Feb', 'Mar']
print(months[6:9]) # ['Jul', 'Aug', 'Sep']
print(months[:3]) # ['Jan', 'Feb', 'Mar'] — start defaults to 0
print(months[9:]) # ['Oct', 'Nov', 'Dec'] — end defaults to end of list
print(months[::2]) # Every other month: ['Jan', 'Mar', 'May', ...]
print(months[::-1]) # Reversed: ['Dec', 'Nov', 'Oct', ...]
Unlike some languages, Python lists can mix types freely:
profile = ["Alice", 28, 5.7, True, ["Python", "SQL"]]
print(profile[0]) # 'Alice' — string
print(profile[1]) # 28 — integer
print(profile[4]) # ['Python', 'SQL'] — a list inside a list!
Use a for loop to visit every item in a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
Output:
I like apple
I like banana
I like cherry
To also get the index, use enumerate():
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
Output:
0: apple
1: banana
2: cherry
List comprehension is a compact way to create a new list based on an existing one. It reads almost like plain English.
# Traditional way
squares = []
for n in range(1, 6):
squares.append(n ** 2)
# List comprehension — same result, one line
squares = [n ** 2 for n in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
# With a condition
even_squares = [n ** 2 for n in range(1, 11) if n % 2 == 0]
print(even_squares) # [4, 16, 36, 64, 100]
The pattern is: [expression for item in iterable if condition]
Let's build something practical. A teacher wants to enter student scores one by one and get a summary report at the end.
scores = []
while True:
entry = input("Enter score (or 'done' to finish): ")
if entry.lower() == 'done':
break
scores.append(float(entry))
if scores:
print(f"\n--- Score Report ---")
print(f"Scores: {scores}")
print(f"Count: {len(scores)}")
print(f"Average: {sum(scores)/len(scores):.1f}")
print(f"Highest: {max(scores)}")
print(f"Lowest: {min(scores)}")
scores.sort()
print(f"Sorted: {scores}")
How it works:
scores = [] — starts with an empty listwhile True: — loops indefinitely until we break outentry.lower() == 'done' — case-insensitive check for the exit wordscores.append(float(entry)) — converts the string input to a float and adds to the listif scores: — only runs the report if at least one score was enteredsum(scores)/len(scores):.1f — calculates average, formatted to 1 decimal placeSample Run:
Enter score (or 'done' to finish): 85
Enter score (or 'done' to finish): 92
Enter score (or 'done' to finish): 78
Enter score (or 'done' to finish): 95
Enter score (or 'done' to finish): 88
Enter score (or 'done' to finish): done
--- Score Report ---
Scores: [85.0, 92.0, 78.0, 95.0, 88.0]
Count: 5
Average: 87.6
Highest: 95.0
Lowest: 78.0
Sorted: [78.0, 85.0, 88.0, 92.0, 95.0]
| Operation | Syntax | Example |
|---|---|---|
| Create list | [item1, item2] | nums = [1, 2, 3] |
| Access item | list[index] | nums[0] → 1 |
| Add to end | list.append(item) | nums.append(4) |
| Insert at position | list.insert(i, item) | nums.insert(0, 0) |
| Remove by value | list.remove(item) | nums.remove(2) |
| Remove by index | list.pop(i) | nums.pop() |
| Length | len(list) | len(nums) → 3 |
| Sort | list.sort() | nums.sort() |
| Slice | list[start:end] | nums[0:2] |
| Check membership | item in list | 1 in nums → True |
append() to add, remove() or pop() to deletelist[start:end:step]In the next lesson, we'll explore dictionaries — a different kind of collection where data has labels instead of position numbers.
Get this course's notes on Telegram!
Free cheat sheets, summaries & practice exercises