List
List
🎯 After reading this lesson
After finishing this lesson, you will be able to confidently do the following 3 things.
- ▸✅ List slicing + comprehension
- ▸✅ Choosing list vs tuple + deep copy (copy.deepcopy)
- ▸✅ sort vs sorted (whether the original is modified)
Keep the learning objectives as a checklist, and close the lesson once you can answer all of them.
8 core list concepts — code + output
list = a data structure that is ordered + mutable + can hold any type. The most frequently used data structure in Python.
1. Creating a list
2. Indexing — starts at 0
⚠️ fruits[10] → IndexError: list index out of range
3. Slicing — [start:end]
Key point: The end index is exclusive (not included). [::-1] is the idiom for reversing a list.
4. Adding and removing
5. Searching and checking
6. Sorting
sort() = modifies the original / sorted(x) = returns a new list.
7. Iteration (for)
```python
fruits = ["apple", "pear", "persimmon"]
for fruit in fruits:
print(f
💡 Key points
1. Negative index: -1 refers to the last element
2. Slicing: [start:end:step]
3. sort() modifies the original; sorted() returns a new list
Python basic data structures: a list is an ordered mutable collection, a tuple is immutable, a dictionary holds key-value pairs, and a set holds unique values. Use list comprehension [x for x in lst if cond] for concise creation. Use dict.get(key, default) to safely retrieve values. The collections module provides: Counter, defaultdict, deque, OrderedDict.
🐍 Try running it — List
🤖 Try asking AI like this
Knowing the concepts in this lesson lets you give AI specific instructions. Instead of a vague 'fix this,' you make vocabulary-driven requests — that is the starting point for saving tokens.
- ▸'Convert this for + append into a list comprehension'
- ▸'Check whether deep copy (copy.deepcopy) is needed in this code'
Why this saves tokens
Without knowing the concepts, even after receiving an AI answer you have to ask 'What does that mean?' again. That follow-up question is what eats your tokens. Learn the concept once, and the conversation ends in one round.