Python Lists: Create, Change, Sort and Slice
A list holds an ordered sequence of values in square brackets: ["Python", "SQL"]. Lists can grow and shrink, may contain duplicates, and can mix types, although in practice most lists hold one kind of thing. They are the collection you will reach for most often.
Reading from a list
Indexing and slicing work exactly as they do for strings: langs[0] is the first item, langs[-1] the last, and nums[1:3] returns a new list with the items at positions 1 and 2. len(langs) counts the items and x in langs checks membership.
Changing a list
Unlike strings, lists are mutable: you can change them in place.
append(x)adds one item at the end.insert(i, x)places an item before positioni.remove(x)deletes the first item equal tox(and raisesValueErrorif there is none).pop()removes and returns the last item;pop(i)removes positioni.lst[i] = xreplaces one item.sort()sorts the list in place and returnsNone. The built-insorted(lst)returns a new sorted list and leaves the original alone. Both acceptreverse=True.
Expected output
['Python', 'JavaScript', 'SQL', 'HTML'] 4 JavaScript HTML HTML ['Python', 'JavaScript'] [1, 2, 5, 9] [9, 5, 2, 1] [2, 5] [1, 2, 5, 9, 100]
Names share the same list
The last three lines of the example contain the most common list surprise. copy = nums does not copy anything; it makes a second name for the same list object. Appending through copy therefore changes what nums shows. To get an independent list, write nums.copy(), list(nums) or nums[:]. These are shallow copies: a list of lists still shares the inner lists, and the copy.deepcopy() function handles that case.
For the complete method list with examples, see the lists and dictionaries cheat sheet.
Common mistakes
- Writing
nums = nums.sort().sort()returnsNone, so you lose the list. Callnums.sort()on its own line, or usesorted(). - Using
appendto add several items:a.append([4, 5])adds one nested list. Usea.extend([4, 5]). - Reading past the end:
a[10]on a short list raisesIndexError, though slices likea[5:10]simply return fewer items.
Summary
- Lists are ordered, mutable and written with square brackets.
append,insert,remove,popandsortchange a list in place.sorted()returns a new list;sort()returnsNone.- Assignment shares a list; use
.copy()for an independent one.
Quiz: Lists