Retrieving the Last Item of a List
Here are few ways in which we can get the last element from a list in Python
Python: 3.0    Anurag Rana    11 Jul 2021   0
Login to upvote
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
my_list = ['red', 'blue', 'green']

# Get the last item with brute force using len
last_item = my_list[len(my_list) - 1]

# Remove the last item from the list using pop
last_item = my_list.pop() 

# Get the last item using negative indices *preferred & quickest method*
last_item = my_list[-1]

# Get the last item using iterable unpacking
*_, last_item = my_list
Copy | Download as: .py file   PNG
Share on: FB   Twitter   LinkedIn   WA
©2021 - code108labs   Contributors   Hosted on DigitalOcean   Partner website: pythoncircle.com