r/developers_talk • u/ak_developers • May 14 '25
Python Simple Codes
What will be the output?
numbers = [1, 2, 3, 4, 5]
print(numbers[::-1])
Can you explain how this works?
1
Upvotes
r/developers_talk • u/ak_developers • May 14 '25
What will be the output?
numbers = [1, 2, 3, 4, 5]
print(numbers[::-1])
Can you explain how this works?
2
u/vladdar May 15 '25
Explanation:
The expression:
numbers[::-1]uses Python list slicing with the following syntax:
list[start:stop:step]Breakdown:
start: Where to start (default is 0 if omitted).
stop: Where to stop (default is the end of the list if omitted).
step: The interval or stride between elements. If it's negative, it goes in reverse.Breakdown: start: Where to start (default is 0 if omitted). stop: Where to stop (default is the end of the list if omitted). step: The interval or stride between elements. If it's negative, it goes in reverse.
start and stop are omitted (defaults to entire list).
step is
-1, meaning:Start from the end (
5).Move backward one element at a time.
Thus, it reverses the entire list.
[5, 4, 3, 2, 1]