Syllabus Lesson 29 of 239 · Data Structures
Data Structures

List Methods and Slicing

Lists come with handy methods that change them in place.

nums = [3, 1, 2]
nums.append(4)      # add to the end  -> [3, 1, 2, 4]
nums.insert(0, 9)   # insert at index -> [9, 3, 1, 2, 4]
nums.remove(9)      # remove first 9  -> [3, 1, 2, 4]
last = nums.pop()   # remove + return last -> last is 4, nums is [3, 1, 2]
nums.sort()         # sort in place   -> [1, 2, 3]

append adds one item; pop() with no argument removes and hands back the last item; pop(0) removes the first.

Slicing copies a range of items using list[start:stop]. The start is included and the stop is excluded:

letters = ["a", "b", "c", "d", "e"]
print(letters[1:3])   # ['b', 'c']  (indexes 1 and 2)
print(letters[:2])    # ['a', 'b']  (from the start)
print(letters[3:])    # ['d', 'e']  (to the end)

A slice returns a brand new list, so the original is untouched.

Your turn

Start from nums = [5, 2, 8, 1]. Append 3, then sort the list. Save the middle two items (a slice nums[1:3]) into a variable called middle.

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output