Slicing Lists

Occasionally, we will need to need to work with a portion of a list, rather than the entire list. Slicing is a method of creating a sublist of consecutive elements drawn from another list. Assume that myList is a Python list, and let i and j be integers.

  • myList[i:j] will generate a sublist of myList that begins with the element at index i and contains all elements up to but not including the element at index j.

  • myList[i:] will generate a sublist of myList that begins with the element at index i and contains all later elements.

  • myList[:j] will generate a sublist of myList that contains all elements up to but not including the element at index j.

# Simple Slicing Example
simpleList = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

print(simpleList[3:7])
print(simpleList[5:])
print(simpleList[:8])
[6, 8, 10, 12]
[10, 12, 14, 16, 18, 20]
[0, 2, 4, 6, 8, 10, 12, 14]

We can also use negative indices when specifying a slice of a list.

# Print the last 6 elements of simpleList
print(simpleList[-6:])
[10, 12, 14, 16, 18, 20]
# Print all but the first two and last two elements of simpleList
print(simpleList[2:-2])
[4, 6, 8, 10, 12, 14, 16]

Example: Quarterly Sales

CompCo is an company that manufactures laptop computers. The list sales below provides CompCo’s total monthly sales for each month of 2016, measured in US dollars. The results are listed in order of month.

sales = [52353, 43724, 32191, 34914, 44671, 37139, 49341, 
         57139, 55104, 45193, 52167, 61294]

CompCo needs to calculate their quarterly sales for each quarter in 2016.

Define four new variables Q1, Q2, Q3, and Q4 in the next cell.

  • Q1 contains the total sales for Quarter 1 (January, February, March).

  • Q2 contains the total sales for Quarter 2 (April, May, June).

  • Q3 contains the total sales for Quarter 3 (July, August, September).

  • Q4 contains the total sales for Quarter 4 (October, November, December).

Use a combination of slicing and the sum() function.

Q1 = sum(sales[0:3])
Q2 = sum(sales[3:6])
Q3 = sum(sales[6:9])
Q4 = sum(sales[9:])

Print the variables Q1, Q2, Q3, and Q4.

print(Q1)
print(Q2)
print(Q3)
print(Q4)
128268
116724
161584
158654