DEV Community

Cover image for 3 cool things you can do with Python indexing
Maria
Maria

Posted on • Edited on

3 cool things you can do with Python indexing

You can do so much with slicing and indexing in Python! Here are some of my favorite tricks:

1. Easily grab values from the end of a list

If you have a list say animals = ['cat', 'dog', 'squirrel','mouse','dolphin'] and you want to grab the last value you could use animals[len(animals - 1)].

However, Python offers you a way to easily access values from the other end of the list with negative indices:

animals = ['cat', 'dog', 'squirrel','mouse','dolphin']

animals[-1] -> 'dolphin'
animals[-2] -> 'mouse'
animals[-5] -> 'cat'
Enter fullscreen mode Exit fullscreen mode

2. Reverse a list

If you want to reverse a list you could use a for loop or the built-in reversed() method...

OR... you can use Python slicing and negative indices:

num_list = [4, 6, 3, 2, 1]
reversed_num_list = num_list[::-1]
print(reversed_num_list) -> [1,2,3,6,4]
Enter fullscreen mode Exit fullscreen mode

One thing to remember is that slicing returns a new list, so using [::-1] will return a new list and it doesn't modify the original list. This also applies to the next trick!

3. Skip every n-th element is a list

If you have a list and you want to select every other element in it, Python easy way to do this is:

num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
num_list[::2] -> [1, 3, 5, 7, 9]
Enter fullscreen mode Exit fullscreen mode

Let's unpack what's going on in here:

  • ':' tells Python to look at the whole list from start to finish
  • ':2' tells Python to skip every other element of the list

You can customize this by providing the start and the steps to skip:

num_list[3::2] -> [4, 6, 8]
Enter fullscreen mode Exit fullscreen mode

You can provide the end and the steps to skip:

num_list[:6:2] -> [1, 3, 5]
Enter fullscreen mode Exit fullscreen mode

Or by providing the start, end and the steps to skip:

num_list[3:-2:2] -> [4,6]
Enter fullscreen mode Exit fullscreen mode

You can even combine it with the previous tip and reverse your list whilst skipping elements!

num_list[::-2] -> [9, 7, 5, 3, 1]
num_list[-2::-2] -> [8, 6, 4, 2]
Enter fullscreen mode Exit fullscreen mode

Of course, this is just a short list of python’s capabilities, but these are the things that impressed me the most when I started learning.

I encourage you to play around with the indices and slicing as this is the best way to get familiar and comfortable with them!


Thanks for reading! If you want you can follow me here or on Twitter

Top comments (10)

Collapse
 
habilain profile image
David Griffin

Two important things: Firstly, the second two examples are slicing, not indexing.

Second off, slicing doesn't quite work how you think it does (assuming you think x[::-1] == reversed(x), which your post seems to imply). Creating a slice creates a copy of that list segment. Pythons memory model means you don't copy the contents itself, but you're creating more references to the objects in the copy at around 28 bytes an element. So if you're memory constrained, or working with really big lists, you should probably use generators - like reversed (because reversed(x) != x[::-1]; they're not even the same type).

Collapse
 
mariamodan profile image
Maria

Thank you for your observations! I didn't mean to imply that think x[::-1] == reversed(x), just that reversed is another way to reverse a list. It completely escaped my mind that slicing creates new lists, I've edited the post to include it :)

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.

Collapse
 
daksamit profile image
Dominik Aksamit

The article brings me thought about similar solution in javascript.
Of course, there is a serious lack of something like negative indexing (you need access with arr[arr.length -1])
But, proxies come to the rescue!
it's something like a wrapper object for your data give them superpowers. Let me show you a simple example with arrays:

let arr = [4, 6, 3, 2, 1]

const arrProxy = {
  get(target, prop, receiver) {
    if (prop.startsWith('::')) {
      prop = +prop.slice(2)
      if (prop < 0) {
        return target.reverse().filter((n, i) => (i + 1) % prop === 0)
      }
      return target.filter((n, i) => (i + 1) % prop === 0)
    } else if (prop < 0) {
      prop = +prop + target.length
    }
    return Reflect.get(target, prop, receiver)
  },
}
arr = new Proxy(arr, arrProxy)

console.log(arr['::-2']) // [2, 6]
console.log(arr[-1]) // 1

arrProxy applies an internal method that gives an ability to do more with your objects.
the prop is always a string, so we need to convert it into a number.
Another caveat - In js ':' is the invalid syntax in this case so wrapping '::-2' in quotes as string

More about proxy:

Collapse
 
mariamodan profile image
Maria

That's a really nice workaround to use slicing and negative indexes in JavaScript! I do wish sometimes that js array would be as neat to work with as python lists haha

Collapse
 
daksamit profile image
Dominik Aksamit

Maybe someday :)
Generally, proxies are a really interesting way to enhance javascript objects and arrays and use them in a way we didn't even imagine what is possible :D

Collapse
 
georgeoffley profile image
George Offley

This is a great find. A lot of this people see some of this in interview questions. Nice work!

Collapse
 
mariamodan profile image
Maria

Thank you!