How to Get Last Items of a List in Python

How do I get the last element of a list?

some_list[-1] is the shortest and most Pythonic.

In fact, you can do much more with this syntax. The some_list[-n] syntax gets the nth-to-last element. So some_list[-1] gets the last element, some_list[-2] gets the second to last, etc, all the way down to some_list[-len(some_list)], which gives you the first element.

You can also set list elements in this way. For instance:

>>> some_list = [1, 2, 3]
>>> some_list[-1] = 5 # Set the last element
>>> some_list[-2] = 3 # Set the second to last element
>>> some_list
[1, 3, 5]

Note that getting a list item by index will raise an IndexError if the expected item doesn't exist. This means that some_list[-1] will raise an exception if some_list is empty, because an empty list can't have a last element.

How to get last items of a list in Python?

You can use negative integers with the slicing operator for that. Here's an example using the python CLI interpreter:

>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> a[-9:]
[4, 5, 6, 7, 8, 9, 10, 11, 12]

the important line is a[-9:]

Detect If Item is the Last in a List

Rather than try and detect if you are at the last item, print the comma and newline when printing the next (which only requires detecting if you are at the first):

a = ['hello', 9, 3.14, 9]
for i, item in enumerate(a):
if i: # print a separator if this isn't the first element
print(',')
print(item, end='')
print() # last newline

The enumerate() function adds a counter to each element (see What does enumerate mean?), and if i: is true for all values of the counter except 0 (the first element).

Or use print() to insert separators:

print(*a, sep=',\n')

The sep value is inserted between each argument (*a applies all values in a as separate arguments, see What does ** (double star) and * (star) do for parameters?). This is more efficient than using print(',n'.join(map(str, a))) as this doesn't need to build a whole new string object first.

How to obtain the last index of a list?

len(list1)-1 is definitely the way to go, but if you absolutely need a list that has a function that returns the last index, you could create a class that inherits from list.

class MyList(list):
def last_index(self):
return len(self)-1

>>> l=MyList([1, 2, 33, 51])
>>> l.last_index()
3

How to extract the last item from a list in a list of lists? (Python)

I would suggest looping through the list twice, like so:

lst = [[[11, 12, 15], [12, 13, 14], [13, 14, 15], [14, 15, 17], [15, 16, 17]], [[14, 15, 18], [15, 16, 17]]]

# Result of iteration
last_lst = []

# Iterate through lst
for item1 in lst:
# Initialize temporary list
last_item1 = []

#Iterate through each list in lst
for item2 in item1:
# Add last item to temporary list
last_item1.append(item2[-1])

# Add the temporary list to last_lst
last_lst.append(last_item1)


Related Topics



Leave a reply



Submit