List playground: change a list one operation at a time
Each button runs one line of real Python on the list. Watch which box changes, what the method gives back, and the error you get when an operation is impossible.
Change the list
Ask a question (the list stays the same)
tasks.Your code so far (ready to paste into Jupyter)
Trace: the list after each line
What to notice
append,insert,remove,sortchange the list and give backNone.pop()is different: it removes the item and hands it back.- After
insertorremove, the positions of later items shift by one.
Try this
Slicing: take any part of a list or string
A slice [start:stop:step] starts at start, goes up to but not including stop, jumping step positions each time. Leave a part blank to use its default.
One item:
What to notice
- The stop position is never included:
[1:3]gives positions 1 and 2. - Slices never raise IndexError: positions past the end are just cut off. A single index past the end does fail.
- A negative step walks backwards, so
[::-1]reverses.
Try this
Ask the list: statistics without a loop
Edit the marks. Every expression on the right is recalculated, and the chart marks the highest, the lowest and the average.
sorted() or .sort()?
Your own expression (use marks and x)
What to notice
sum(marks) / len(marks)is the average, and it is always a float.sorted(marks)makes a new list;marksitself does not change.sorted(marks)[-2]is "second largest" only when the top mark is not repeated.
Try this
Two names, one list: what = really does
A name is a label with an arrow to a value. b = a copies the arrow, not the list. Step through and watch the arrows.
Output
Names and the values they point to
What to notice
- Two arrows to one list means one list: a change through either name shows through both.
.copy()builds a second, separate list.- Tuples and strings cannot be changed in place, so sharing them is always safe.