-3

In the below code I want to print the first two values using slicing. But I get only one value in the output. Is there anyone who can understand what is happening?

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

Output is: [2]

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 3
    List indices start at 0, not 1, so the slice `[1:2]` is certainly not going to include the first element of the list... – jasonharper Aug 11 '22 at 22:55
  • Right. `a_list[0:2]` says "start with element #0, and end just before element #2." – Tim Roberts Aug 11 '22 at 22:58
  • 1
    https://stackoverflow.com/questions/509211/understanding-slicing – AcK Aug 11 '22 at 23:00
  • 1
    Did you search "[slicing in Python](https://duckduckgo.com/?q=slicing+in+Python)"? You are [expected to do some research](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) before asking people to give you a solution. – Ignatius Reilly Aug 11 '22 at 23:01
  • See [Hans' answer](/a/509297/4518341) on the linked duplicate – wjandrea Aug 11 '22 at 23:17

1 Answers1

1

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]
wjandrea
  • 28,235
  • 9
  • 60
  • 81
MoRe
  • 2,296
  • 2
  • 3
  • 23
  • 1
    Technically, it's not an operator. Check out the discussion on [Slice "colon operator" nomenclature](/q/33520674/4518341) – wjandrea Aug 11 '22 at 23:27