I don't understand how this code works?? | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 2

I don't understand how this code works??

nums = (55, 44, 33,22) print (nums[:2][-1])

15th Mar 2024, 3:20 PM
Artin
Artin - avatar
3 Réponses
+ 5
It's called list slicing. list[start:stop:step] Here you have only [:2] means, start is index 0 (default), stop is index 2, step is 1 (default) For more read here: https://www.programiz.com/JUMP_LINK__&&__python__&&__JUMP_LINK-programming/examples/list-slicing So nums[:2] -> (55,44) 55 is at index 0, 44 is at index 1. Since you stopped at index 2 33 is not part of your list. [-1] means in python the last index. [-2] would be the second last index. nums[:2][-1] prints 44 because 44 is the last element of (55,44)
15th Mar 2024, 4:15 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
Ohh yesss I understand Thanks alottt
15th Mar 2024, 4:37 PM
Artin
Artin - avatar
0
This code prints the last element of the first two elements in the tuple `nums`. Let's break it down: - `nums[:2]` selects the first two elements of the tuple: `(55, 44)`. - `nums[:2][-1]` then selects the last element of this result, which is `44`. So, the output of the code would be `44`.
16th Mar 2024, 12:02 PM
Rohit Krishna
Rohit Krishna - avatar