List Indexing and Slicing

Imagine you have a row of lockers. To find your books, you need the locker number! In Python, we call these locker numbers Indexes. If you want to grab a whole row of lockers at once, we use Slicing.

What is List Indexing?

Indexing is used to access one specific item using its position number.

  • Zero-Based: In Python, the first item is always at index 0.

  • Negative Indexing: You can also count backward! The very last item in a list is at index -1.

What is List Slicing?

Slicing is used to cut out a specific "slice" or range of items from your list. It uses the colon (:) operator.

  • The Rule: Slicing includes the start index but stops right before the stop index (it is exclusive of the stop value).

Real-World Scenarios

  • Top Scores: Slicing the first 3 items to see the winners.

  • Last Song: Using index -1 to play the final track in a playlist.

  • Recent Items: Slicing the end of a list to see the most recent tasks.

How it Looks (Syntax & Examples)

The Pattern:

list[index]        # Get one item
list[start:stop]   # Get a range of items


Example 1: Basic Indexing

numbers = [10, 20, 30, 40]
print(numbers[1])


Output: 20

Example 2: Slicing a Range

numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])

Output: [20, 30, 40]

Summary:

  • Fast Access: Indexing is the fastest way to grab a single value.

  • New Lists: Slicing doesn't change the original list; it creates a new smaller list.

  • Be Careful: If you try to access an index that doesn't exist, Python will give you an "IndexError."

Check your knowledge

Quickly verify what you've learned from this tutorial.

Question 1

What is the index of the second item in a Python list?

Because we start counting at 0, the second item is always at index 1.

Question 2

Which symbol is used for slicing a list?

The colon (:) is the standard operator used to define a range for slicing.

Question 3

If names = ["Ali", "Bob", "Dan"], what does names[-1] return?

Negative indexing starts from the end, so -1 always represents the last item in the list.

Question 4

Look at nums = [5, 10, 15, 20]. What is the result of nums[0:2]?

Slicing starts at index 0 and goes up to, but does not include, index 2.

Question 5

What happens if you try to run print(my_list[10]) on a list that only has 3 items?

Python throws an error if you try to access a position that is outside the boundaries of the list.

Congratulations!

You've successfully mastered the knowledge check for "List Indexing and Slicing."

For more questions and practice, click the link below:

Practice More Questions
Previous Topic Creating Lists Next Topic List Operations (append, remove, pop)