PyPyPath

Module 5: Lists in Python

Slicing Lists

Slicing a list gives you a smaller list (a sub-list). Same rules as strings: [start:end], end not included.

About 10 minutes

Example code
nums = [0, 1, 2, 3, 4, 5]
print(nums[1:4])   # [1, 2, 3]
print(nums[:3])    # [0, 1, 2]
print(nums[3:])    # [3, 4, 5]
print(nums[::2])   # every 2nd item

Slicing creates a new list — the original list is not changed.

Practice

From data = [10,20,30,40,50], slice the middle three numbers.

Key takeaways

  • [start:end] copies items from start up to (not including) end.
  • Slicing returns a new list.
  • Works the same way as string slicing.

Quick check: Slicing Lists

Question 1 of 2

What is [0,1,2,3,4][1:4]?