DEV Community

Discussion on: 3 cool things you can do with Python indexing

Collapse
 
mxldevs profile image
MxL Devs

An interesting syntax. Feels like something I'd only use for code golfing though lol. What's the performance comparison between using reverse, or using a standard for loop

Collapse
 
mariamodan profile image
Maria

Haha yeah on a regular basis I only use negative indexes to grab the last couple values in a list.

That's actually a really good question 🤔 It's 9 pm here so I'll look into it tomorrow and probably write another post it 💪

Collapse
 
mxldevs profile image
MxL Devs

Negative indexing is a god-send.

In Java, I can't do negative indexing, so I always need to say "length - 1" to get the last element instead of just -1. This becomes annoying because for example if I wanted to split a string into an array and grab the last element (which might not always be the last character for example), I need to store the split results into a variable just so I can access the length, and then subtract 1.

Actually I guess python lists basically store the length as a property, so -1 is possible because you don't need to calculate the length separately.