Lists — append, slice, sort, comprehensions
Lists are ordered, mutable, indexed. The most-used Python data structure.
script.py
v3.1
Python output
click Run to execute
Click "Run" to execute the code on the left.
The output will appear here.
The output will appear here.
🧠 How it works
Lists are arrays that grow/shrink. Indexed 0, 1, 2, ... and -1, -2, -3 from the end. slice [start:stop:step] — start INCLUSIVE, stop EXCLUSIVE. nums[1:4] gives indices 1, 2, 3. Omitting start/stop means 'from beginning' / 'to end'. nums[::-1] reverses. append(x) adds to end. extend(iter) adds all from iter. insert(i, x) puts x at index i. remove(x) removes the FIRST x. pop() removes and returns the last. sort() sorts in place (returns None). sorted() returns a new sorted list (doesn't mutate). Comprehension [expr for x in list if cond] — faster than a for+append loop.
✏️ Try these changes
-
Change nums[:3] to nums[3:]→ last 5 instead of first 3 -
Change nums[::2] to nums[::3]→ every 3rd element -
Change nums.sort(reverse=True) to nums.sort()→ ascending order -
Change [x * 2 for x in nums] to [x * 2 for x in nums if x > 4]→ only doubles values > 4 -
Add nums.clear()→ empties the list