Python Tutorial 0/52 lessons ~6 min read Lesson 17
Lists
Lists are mutable, ordered sequences — Python's workhorse collection.
Course progress0%
Focus
9 guided sections
Practice signal
Examples included
Career prep
Interview Q&A included
Introduction
Lists are mutable, ordered sequences — Python's workhorse collection. Backed by a dynamic array; O(1) index, O(n) insert/remove in middle.
Understanding the topic
Core concepts to understand:
- Create:
[1, 2, 3]orlist(). - Append O(1), pop end O(1), insert middle O(n).
- Slicing creates a copy:
xs[1:3]. - Sort in place:
xs.sort(); new list:sorted(xs).
Syntax reference
Visual flow / code:
python
xs = [3, 1, 4, 1, 5, 9]xs.append(2) # [3,1,4,1,5,9,2]xs.insert(0, 0) # [0,3,1,4,1,5,9,2]xs.remove(1) # removes first 1xs.pop() # removes & returns lastxs.sort() # in placetop3 = sorted(xs)[-3:]copy = xs[:] # full copy
Execution workflow
1Lists Workflow
1 / 4Create
[1, 2, 3] or list().
Real-world use
Lists are the default container for ordered data — request bodies, query results, batches. Use collections.deque if you need fast O(1) prepend.
Best practices
- Use
append, not+=, in loops. - Slice to copy — never share mutable lists by reference accidentally.
Common mistakes
a = b = []makes both names point to the same list.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionList vs tuple?+
Answer
A list is mutable and dynamic, while a tuple is immutable and fixed after creation. Lists suit collections that change, and tuples suit fixed records and can be hashable if their contents are. Tuples can be slightly smaller and faster to create, but the main reason to choose one is intent and hashability, not speed.
2IntermediateQuestionWhen use deque?+
Answer
Use
collections.deque when you need fast appends and pops at both ends, such as queues, sliding windows, and BFS. A list is O(n) for pop(0) and insert(0, x) because elements shift, while a deque does these in O(1). A deque is slower for indexing into the middle, which is O(n), so use a list for random access.Follow-up
How does deque(maxlen=n) behave when full?
3IntermediateQuestionBig-O of list ops?+
Answer
List indexing and
append are O(1) (append amortized), pop() from the end is O(1), and pop(0), insert, and remove are O(n). Membership with in and index are O(n), slicing is O(k) for the slice size, and sort is O(n log n). Appends are amortized because the list occasionally over-allocates and resizes.Follow-up
Why is append amortized O(1) rather than strictly O(1)?
Summary
In summary: Lists = mutable ordered. Append O(1), middle insert O(n).
Ready to mark this lesson complete?Track your journey across the entire course.