livepython.net
CHAPTER 09Python Lists
9.6  PRACTICE

Python List Practice Questions for Beginners

Chapter 9 Recap and Practice

Your programs can now keep many values in one place. Here is the chapter in one table:

You writeIt does
items = ["a", "b"]makes a list; [] is an empty list
len(items)counts the items
a + b, [0] * 3joins two lists, repeats a list
items[0], items[-1]the first item, the last item
items[1] = "x"changes the item at index 1
items[1:3]a slice: index 1 up to, not including, 3
items[:3], items[-2:]the first 3 items, the last 2 items
items[::-1], items[:]a reversed copy, a copy
items.append(x)adds x at the end
items.insert(0, x)adds x at index 0
items.remove(x)removes the first x
items.pop(), del items[0]removes by index (pop() gives the item back)
x in itemsTrue when x is in the list
items.sort(), sorted(items)sorts the list, gives a new sorted list
min(), max(), sum()the smallest, the largest, the total
items.count(x), items.index(x)how many times, and where

And the errors to watch for: IndexError (an index past the end), ValueError (removing or finding a value that isn't there), and None (storing what append() or sort() gives back).

Practice questions

Use input() with no prompt text. The tests try several inputs, including the edges (like 0, or one more than the length of the list), so test your program with those too.

Python lists

  1. 70.Python Program to Create and Print a ListEasySolve
  2. 71.Python Program to Build a Seat List with + and *MediumSolve

List index

  1. 72.Python Program to Print the First and Last Item of a ListEasySolve
  2. 73.Python Program to Find the Day Name from Its NumberMediumSolve

List slicing

  1. 74.Python Program to Print the Top Three ScoresEasySolve
  2. 75.Python Program to Get the Last Few Temperatures from a ListMediumSolve

Add and remove items

  1. 76.Python Program to Add Items to a Shopping ListEasySolve
  2. 77.Python Program to Remove a Task by Its NumberMediumSolve

List tools

  1. 78.Python Program to Check If an Item Is on the MenuEasySolve
  2. 79.Python Program to Make a Class Marks ReportHardSolve

Lists hold your data in order. Next, you'll learn the for loop, which visits every item for you.