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]
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]
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:
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]
[:4]
means [0:4]
, [0:]
means [0:last_index+1]
, and [:]
means [0:last_index+1]