Lists

Part of the free LogicWiz Python course, Module 5: Lists and tuples. The examples and practice run in the app.

Shankar bhaiya's canteen sells 40 items. Aarav started writing item1 = "Samosa", item2 = "Chai"… and gave up at item 6. One list holds all 40 under one name.

You'll learn to

  • Make a list, read items by index and slice it
  • Grow and shrink a list with append, extend, insert, remove and pop
  • Know why `sort()` gives back None while `sorted()` gives a new list

Learn

Many values, one name

A list is an ordered row of values inside square brackets: menu = ["Samosa", "Chai", "Maggi"].

  • Indexes start at 0, just like strings. menu[0] is the first item, menu[-1] the last.
  • Slicing works too: menu[1:3] gives a new list of items 1 and 2.
  • len(menu) is the number of items.

The big difference from a string: a list is mutable. You can change an item in place with menu[1] = "Masala Chai". A string never allows that.

Index, slice, change

menu = ["Samosa", "Chai", "Vada Pav", "Maggi"]
print(menu[0])
print(menu[-1])
print(menu[1:3])
print(len(menu))
menu[1] = "Masala Chai"
print(menu)

Step through and watch menu change in place at line 6. Try menu[4]: there is no item 4, so you get an IndexError.

Adding and removing

MethodWhat it does
lst.append(x)adds one item x at the end
lst.extend([x, y])adds each item of another list at the end
lst.insert(i, x)puts x at index i, shifting the rest right
lst.remove(x)deletes the first item equal to x (ValueError if none)
lst.pop() / lst.pop(i)deletes the last item (or item i) and returns it
del lst[i]deletes item i, returns nothing

Meher's cart

cart = ["Chai"]
cart.append("Samosa")
cart.extend(["Maggi", "Vada Pav"])
cart.insert(0, "Water")
print(cart)
cart.remove("Maggi")
last = cart.pop()
print(last)
first = cart.pop(0)
print(first, cart)

Change extend to append on line 3 and run again. Count the items.

cart.append(["Maggi", "Vada Pav"]) does not add two items. It adds one item, which is itself a list: ['Chai', 'Samosa', ['Maggi', 'Vada Pav']]. Use extend to add each item.

sort() vs sorted()

marks = [72, 95, 60, 88]
ranked = sorted(marks, reverse=True)
print("ranked:", ranked)
print("marks :", marks)

result = marks.sort()
print("result:", result)
print("marks :", marks)

sorted(marks) makes a new sorted list and leaves marks alone. marks.sort() sorts marks itself and returns None.

Asking questions of a list

prices = [15, 10, 30, 20, 10]
print(30 in prices, 50 in prices)
print(sum(prices), max(prices), min(prices))
print(prices.count(10), prices.index(30))
for p in prices:
    print("Rs", p)

CBSE Class 11 asks these every year, often as 1-2 mark "predict the output" questions: append vs extend, remove vs pop, and sort() vs sorted(). Remember: remove takes a value, pop takes an index and gives the item back.

In one line

append adds one item, extend adds many; remove takes a value, pop an index; sort() changes the list and returns None, sorted() returns a new list.