Skip to content
Foxipa

Suggest an edit

Tell us what should be corrected, clarified, or improved. Submission will be connected to Foxipa’s contribution service later.

No information is sent anywhere yet. Your suggestion is only prepared in your browser.

Learning

Python Lists

Learn the workhorse container: creating lists, indexing and slicing them, growing and shrinking them in place, and reading them with a for loop.

Levels: Beginner ~15 min read

Basic

Most programs sooner or later hold a pile of things rather than one thing, and Python's answer is the list: an ordered, changeable sequence written in square brackets. Order matters, duplicates are welcome, and unlike strings, a list changes in place, which is the fact behind nearly every surprise lists have to offer.

Making and reaching into lists

python basics.py
1
2
3
4
5
6
breads = ["sourdough", "rye", "flatbread"]

breads[0]     # "sourdough"   positions count from zero
breads[-1]    # "flatbread"  negatives count from the end
breads[1]     # "rye"
len(breads)   # 3

Indexing works exactly as it does on strings.

Everything true of string indexing and slicing is true here: breads[0:2] is a new list of the first two items, stop-exclusive, negative positions count from the end. The difference arrives when you assign: breads[0] = "ciabatta" replaces an item in place, no error, because lists are mutable and strings are not.

Growing and shrinking in place

Lists change themselves rather than returning changed copies, and the methods to know by heart are the ones below. Note what each one returns, because append returns None , and the beginner classic is writing items = items.append(x) and losing the list to it.

The in-place toolbox, and what each call hands back.

Statement

Effect on the list

Returns

breads.append("bagels")

Adds one item at the end.

None

breads.insert(1, "buns")

Slides an item into position 1.

None

last = breads.pop()

Removes and returns the last item.

The removed item

first = breads.pop(0)

Removes and returns position 0.

The removed item

breads.remove("rye")

Deletes the first matching item.

None

breads.sort()

Sorts the list in place.

None

breads.reverse()

Reverses in place.

None

Membership, and copying honestly

in asks whether a value lives in the list, a plain, fast question that replaces loops full of flag variables. Copying is where lists bite once more: a = b copies nothing, it gives one list a second name, and appending through either name shows up in both. A real copy is b[:] or list(b), and a deep copy of nested lists is a question for the copy module, a deliberate trip, not an accident.

python alias.py
1
2
3
4
5
6
7
breads = ["sourdough", "rye"]
alias = breads                    # a second name
copy = breads[:]                  # an honest copy

breads.append("bagels")
len(alias)   # 3  followed the change
len(copy)    # 2  stayed behind

Names point at lists; slices make new ones.

Reading a list with for

The for loop walks a list item by item, handing each one to a name you choose. Python's for is a for-each: there is no index unless you ask for one, and most loops are cleaner for never having counted.

python for.py
1
2
3
4
5
6
for bread in breads:
    print(f"- {bread}")

# when the position genuinely matters
for index, bread in enumerate(breads):
    print(f"{index + 1}. {bread}")

The loop you will write daily, and its numbered colleague.

Run a small order queue

The example below manages a bakery counter with the whole toolbox. Run it, then work the mutations: add a bread with append, serve the front of the queue with pop(0), and try the alias trap for yourself by adding shadow = queue and appending to either one. The printouts will tell you exactly who is pointing where.

Interactive Runnable example
Edit

Ready to run.

What to notice

  • Every mutation happened in place; no assignment was needed for the list to change.

  • The archive copy stayed two items long while the queue grew, because slicing made a genuinely new list.

  • enumerate with start=1 printed a human-friendly numbered list without managing a counter.


Quick check

If you can explain why items.append(x) must never be assigned to anything, why a = b on lists copies nothing, and what pop(0) does to a queue, containers hold no fear. Next, dictionaries trade order for labels. When you are ready, take the Python Lists quiz.

Was this page helpful?

Mark this learning resource complete to track your learning progress.