+ 1

How to read this?

Hi all! Could anyone walk me through why the output is 3? Not sure what happens here: print([1,2,3,4][1:3][1])

7th Dec 2022, 9:16 PM
Karolina Zieminski
Karolina Zieminski - avatar
7 odpowiedzi
+ 8
# print out the intermediate steps x = [1, 2, 3, 4] print(x) y = x[1:3] print(y) z = y[1] print(z)
7th Dec 2022, 9:42 PM
Lisa
Lisa - avatar
+ 3
It's because the second [] is a list slice. With this, you're just getting the 1 and 2 index of the list. the third [] is the index you're choosing from the slice. Remember that the index begin from 0. So you have: 0=1 1=2 2=3 3=4 The slice gets the 1 to 3. The 3 will not enter in the count. So you'll have: 1=2 2=3 with this you making "a new list". Then you are choosing the [1] from the new list, that is the number 3: 0=2 1=3 I don't know if I made myself clear. haha'
7th Dec 2022, 9:51 PM
Alexandre Leal de Medeiros Martins Moura
Alexandre Leal de Medeiros Martins Moura - avatar
+ 3
The code print([1,2,3,4][1:3][1]) will print the value 3. The code first creates a list containing the numbers 1, 2, 3, and 4. The list is then indexed using [1:3], which returns a new list containing the elements at index 1 and 2 from the original list (i.e., the numbers 2 and 3). This new list is then indexed again using [1], which returns the element at index 1 of the list (i.e., the number 3). Finally, the print function is called to print the value of this element to the screen.
8th Dec 2022, 4:32 AM
Calviղ
Calviղ - avatar
+ 2
print(f'{[1,2,3,4][1:3][1] = }') print(f'{[1,2,3,4][1:3] = }') print(f'{[2,3][1] = }')
7th Dec 2022, 11:46 PM
Bob_Li
Bob_Li - avatar
+ 1
Thank you all! 🙏
8th Dec 2022, 4:29 AM
Karolina Zieminski
Karolina Zieminski - avatar
+ 1
Let's consider [1,2,3,4] which I will assign to a, a = [1,2,3,4] y=[1:3] is slicing of the above list, the result of which is [2,3] If you print the index[1] of the above list, the result is 3, Note the index starts with 0
9th Dec 2022, 7:06 AM
Kishore Kumar
+ 1
Print([1,2,3,4][1:3][1]) In this code first print list [1,2,3,4] 0,1,2,3 --> index Then [1:3] this number index of list which element are store or print That means print index(1or2) [2,3] last number are not count in slicing . After than execute [1] That print index(1) in this list [2,3] Now we got output 3. For more info you can check this code https://code.sololearn.com/cT01Y00uW41l/?ref=app
9th Dec 2022, 10:25 AM
Parth Dave
Parth Dave - avatar