Search code examples
python

Issue with Slicing in Python - Only One Value Returned


I'm trying to use slicing in Python to print the first two values from a list. However, I only get one value in the output, and I can't figure out why. Here's my code:

a_list = [1,2,3]
b_list = a_list[1:2]
print(b_list)

I expected the output to be the first two values, but instead, I get: Output is: [2]

Why is the output only [2]? Can anyone help me understand how slicing works in this case?


Solution

  • What is : in Python? It is an operator for slicing a list and it is an alias for slice(start, end, step) function.

    How can I use it and how it works? When you use it with a list such as [1,2,3] like [1,2,3][0:2] you get all elements from 0th to first. In fact, 2 is excluded.

    And please mind that array indices start from 0, so 1 is the 0th element of the list:

    [1,2,3][0] == 1 # True
    

    And if you want to get all elements you can use [1,2,3][0:3].

    Two more points:

    1. There is another part: step like [start:end:step] and you can specify step size, for example [1,2,3,4][0:4:2] will give you [1,3]
    2. You can omit any part of a slice: [:4] means [0:4], [0:] means [0:last_index+1], and [:] means [0:last_index+1]