Python foundations

Python Lists: Indexing, Methods, and Sorting

See how Python lists store ordered items, count duplicates, and change in place. Compare append, extend, remove, pop, and sorted.

A Python list is an ordered collection you can change. Create one with square brackets, read the first item with items[0], and count its entries with len(items). A list keeps duplicates, so a route can include the same stop twice.

stops = ["library", "park", "library"]
assert len(stops) == 3
assert stops[0] == "library"
assert stops[-1] == "library"
assert stops.count("library") == 2

len(stops) counts all three entries. stops.count("library") counts the two matching entries. With three items, the last nonnegative index is two. Trying stops[3] raises IndexError, while stops[-1] reads the last item.

List indexes, length, and value lookup

A position is useful when it carries meaning. The first entry in a chronological list might be the earliest observation. If you only need to know whether an entry occurred, "park" in stops reads more clearly than a loop that counts every match. To find the position of the first match, use stops.index("park"). It returns 1 and raises ValueError if the value is absent.

Lists can contain mixed types. A list like ["park", 3, True] is valid, but its positions need an agreed meaning. Three months later, the person reading row[2] has to remember what the flag meant. Use a dictionary when named fields convey the structure more clearly. A list of dictionaries works well for an ordered collection of records with the same named fields.

Add, replace, or remove an item

append(x) adds one item at the end. extend(other) adds each item from other. Assign to an index to replace that entry. To delete by value, use remove(x), which acts on the first match. To take an item by position and keep using it, use pop(i).

names = ["Mina", "Joel"]
names.append("Inez")
names.extend(["Omar", "Bea"])
names[1] = "Jo"
assert names == ["Mina", "Jo", "Inez", "Omar", "Bea"]

If you call names.append(["Omar", "Bea"]), the new entry is itself a list. If you call names.extend("Omar"), the new entries are the four characters of the string. Extend consumes an iterable, which means both behaviors are consistent with the rule even when they surprise you.

A method that changes the existing list and returns no particular result often returns None. names = names.sort() therefore replaces your reference with None. If you want to keep the original order, sorted(names) creates a separate list. Use names.sort() as its own statement if the original list should be rearranged.

Check who shares the list

Names refer to objects. Assigning the original list to a second name gives both names a reference to the same list. If you append through either name, the other name sees the addition. Use copy() to make a new outer list before making independent changes.

morning = ["tea", "toast"]
same_order = morning
evening = morning.copy()

same_order.append("fruit")
evening.append("soup")

assert morning == ["tea", "toast", "fruit"]
assert evening == ["tea", "toast", "soup"]

The copy is shallow. A new outer list can still contain references to the same inner lists or dictionaries. To edit a nested record independently, make an independent copy of that record as well. For two levels of simple data, copying each record explicitly shows a reader which layer you are trying to separate.

A related trap is building empty buckets with [[]] * 3. Repetition puts the same empty list in three positions. To create three separate buckets use [[] for _ in range(3)]. You can check the difference with buckets[0].append("one") and a look at the other two buckets.

Loop without losing track of the collection

Use for name in names when you want every item. Use enumerate(names) when the position matters as well. If you need to remove several entries, create a filtered list from the original. Removing entries from a list while stepping through it can skip items when positions shift.

inbox = ["read", "", "", "reply"]
cleaned = [message for message in inbox if message]
assert cleaned == ["read", "reply"]
assert len(inbox) == 4

A list is also a useful last-in, first-out stack. Add to the end with append and take from that end with pop(). If your work repeatedly takes from the front, collections.deque is designed for operations at both ends. A list can still read the first item easily, but deleting its first entry usually means moving the remaining entries.

When a list is the right choice

Start by asking what a new entry represents. If arrival order and repeated occurrences are both useful, keep a list. If the question is only whether a distinct value has appeared, consider a set. If you need to retrieve a record by a stable key, a dictionary usually makes that relationship clearer. If a small group of fields forms a fixed-length value, such as a pair of coordinates, a tuple may express the idea better.

Before handing a list to another function, decide which component owns it. A function called ordered_copy suggests a new list, while sort_in_place signals a change to the caller’s input. Test an empty list, repeated values, and one normal case. Those three cases make it easier to tell whether your method preserves the properties that made the list useful in the first place.

Sort records without flattening their meaning

For a list of records, tell Python which part should determine the ordering. Extract the comparison key from each record and leave the rest of that record intact. The following operation places the shortest visit first and keeps the original ordering of visits with equal duration.

visits = [("north", 10), ("west", 5), ("east", 10)]
by_duration = sorted(visits, key=lambda visit: visit[1])
assert by_duration == [("west", 5), ("north", 10), ("east", 10)]
assert visits[0] == ("north", 10)

The sort is stable, so “north” stays ahead of “east” when both keys are ten. If an exported report must be independent of arrival order, add a second comparison key such as the site name. If original arrival order carries meaning, keeping it as the implicit tie-breaker can be the better choice.

Sorting is also where an inconsistent collection becomes obvious. A list can contain both integer durations and string durations, but they cannot be ordered together as ordinary numbers. Normalize the units and parse text durations first. Once the data has the intended shape, the sort expression can be short and clear. See Python data types for the distinction between a count and the text that encodes it.

If the list may have a missing duration, decide what that absence means before sorting. Putting missing data at the end can help people find complete entries, while removing it silently can make a report look more complete than it is.

Sources and further reading

Related reading

Browse Python foundations · Explore project tutorials

Search PythonProjects.org