Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Jessica Temporal
Jessica Temporal

Posted on • Originally published atjtemporal.com on

The last of the list with Python

Python is known for making it easy to write beautiful, small code. Today’s pro tip is about how to get the last element of a list using this language \o/

Coming from other languages like Java or C to Python, it’s normal to bring a bit of an accent to your codes and want to do something more or less like this to get the last element of a list:

my_list = [1, 2, 3, 4, 5]item_index = len(my_list) - 1print(item_index)# 4last_one = my_list[item_index]print(last_one)# 5
Enter fullscreen modeExit fullscreen mode

Use thelen() size function to get the length of the list and subtract1 to get the index of the last element in that list. And that’s ok! It works. However, Python presents a more elegant way of doing this, see:

last_one = my_list[-1]print(last_one)# 5
Enter fullscreen modeExit fullscreen mode

magic gif

Even though it may seem like this, it’s not magic! From thePython documentation:

If i or j is negative, the index is relative to the end of sequences:len(s) + i orlen(s) + j is substituted. But note that-0 is still0.

In a simpler way,Raymond Hettinger explains in this tweet with code:

#python tip: How to support negative indexing:

def __getitem__ (self, i):
if i < 0:
i += len(self)
if i < 0 or i >= len(self):
raise IndexError
...

— Raymond Hettinger (@raymondh)20 de dezembro de 2017

The implementation is actually more complex than this, but what happens in general terms: the__getitem__ method is invoked when we callmy_list[-1] receiving the list itself (self) and the negative index (i) then adds this index with the size of the list and returns the updated index value. Interestingly, this was the same thing I did on the first example but it is already implemented by default.

And a little detail, the same can be done for strings!

word = 'yes'print(word[-1])# s
Enter fullscreen modeExit fullscreen mode

Dope, right? Now just use negative index in your codes too 😉


Links

Special thanks

To Mário Sérgio, Diego Ponciano and Paulo Haddad for some of the links in this post!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

DevRel 🥑 • Author • 🎙Podcaster Pizza De Dados • Creator of gitfichas.com • GitHub ⭐️ • cross-stitcher & knitter • 🇧🇷 & 🇨🇦 • she/her
  • Location
    Canada
  • Pronouns
    she/her
  • Work
    Auth0 by Okta
  • Joined

More fromJessica Temporal

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp