Lecture 3.2 · Interactive lab

Lists Lab

Change a list item by item, slice it any way you like, and see when two names share one list

Introduction to Data Science and Machine Learning
Md Mahbub E Noor · University of Barishal
All labs

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.

x is any Python value: text needs quotes.

Change the list

Ask a question (the list stays the same)

>>>
Pick an operation. Each one runs a single line of Python on tasks.

Your code so far (ready to paste into Jupyter)

Trace: the list after each line

What to notice

  • append, insert, remove, sort change the list and give back None.
  • pop() is different: it removes the item and hands it back.
  • After insert or remove, 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.

Python code
Result

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; marks itself 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.

Try this

Works offline: no internet needed. The Python shown here runs in your browser with the same rules as Python 3, so results and error messages match what you will see in Jupyter.