- Accessing the last element in a list in Python
- 5 Answers 5
- Related
- Hot Network Questions
- Subscribe to RSS
- Python: How to Get the Last Item (or Last n Items) From a List
- How Does List Indexing Work in Python?
- Python: Get the Last Item from a List Using Negative Indexing
- Get the Last n Items from a List Using Negative Indexing
- PyTorch Activation Functions for Deep Learning
- How to Get the Last Item From a Python List and Remove It
- How to get last items of a list in Python?
- 5 Answers 5
- Slicing
- Explanation:
- Give your slices a descriptive name!
- islice
Accessing the last element in a list in Python
I have a list for example: list_a = [0,1,3,1] and I am trying to iterate through each number this loop, and if it hits the last «1» in the list, print «this is the last number in the list» since there are two 1’s, what is a way to access the last 1 in the list? I tried:
if list_a[-1] == 1: print "this is the last" else: # not the last
if list_a.index(3) == list_a[i] is True: print "this is the last"
The thing is, in Python, you just can’t distinguish between those two 1, they are the same object and both list positions point to the same object.
How did your first solution not work? I surely print out this is the last . Should it print this sentence if the last number is 1? If so, it works.
5 Answers 5
list_a[-1] is the way to access the last element
@F.C. The questions says that comparing the last element to 1 didn’t work: list_a[-1] == 1 , which is not the same thing as this answer.
@F.C. Come on Man! You know that in lists list_a[-1] always refers to the last element. The OP is confused on this as there are two elements with the same value in the list. This does not mean that list_a[-1] is wrong. Just that we need to re-affirm to the OP saying that he should not be confused and that list_a[-1] is the correct way to access the last element
@GodMan ok, maybe you should add some explanation to your answer, I don’t think it would help much as it is.
You can use enumerate to iterate through both the items in the list, and the indices of those items.
for idx, item in enumerate(list_a): if idx == len(list_a) - 1: print item, "is the last" else: print item, "is not the last"
0 is not the last 1 is not the last 3 is not the last 1 is the last
Tested on Python 2.7.3
This solution will work for any sized list.
^We count the number of elements in the list and subtract 1. This is the coordinate of the last element.
print "The last variable in this list is", list_a[last]
^We display the information.
a = [1, 2, 3, 4, 1, 'not a number'] index_of_last_number = 0 for index, item in enumerate(a): if type(item) == type(2): index_of_last_number = index
The output is 4, the index in array a of the last integer. If you want to include types other than integers, you can change the type(2) to type(2.2) or something.
To be absolutely sure you find the last instance of «1» you have to look at all the items in the list. There is a possibility that the last «1» will not be the last item in the list. So, you have to look through the list, and remember the index of the last one found, then you can use this index.
list_a = [2, 1, 3, 4, 1, 5, 6] lastIndex = 0 for index, item in enumerate(list_a): if item == 1: lastIndex = index print lastIndex
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Python: How to Get the Last Item (or Last n Items) From a List
In this post, you’ll learn how to use Python to get the last item from a list as well how as how to get the last n items from a list. You’ll learn a total of 4 different ways to accomplish this, learning how to find the best method for your unique solution. Let’s get started!
The Quick Answer: Use Negative Indexing
How Does List Indexing Work in Python?
One of the unique attributes of Python lists is that they are ordered, meaning that their order matters. Because of this, we can access list items by their index positions.
Python lists begin at the 0th index, meaning that to get the first item, you would access index #0. Because of this, if you know how long a list is, you can access its last item by accessing that specific index. Say we have a list of length n, you would access the (n-1)th index.
This, of course, isn’t always practical because you don’t always know how long a list really is. Because of this, you can also access the list from the end, using negative indexing. By accessing the index of -1 , you would be accessing the last item in that list.
See the graphic below for an example of how indexes appear in a list:
Now that you have an understanding of how list indexing works in Python, let’s get started to access the last item in a list.
Python: Get the Last Item from a List Using Negative Indexing
Getting the last item in a Python list using negative indexing is very easy. We simply pull the item at the index of -1 to get the last item in a list.
Let’s see how this works in practice:
a_list = ['datagy', 1,[3,4,5], 14.3, 32, 3] last_item = a_list[-1] print(last_item) #Returns: 3
Similarly, if you wanted to get the second last item, you could use the index of -2 , as shown below:
a_list = ['datagy', 1,[3,4,5], 14.3, 32, 3] second_last_item = a_list[-2] print(second_last_item) #Returns: 32
Now let’s see how to get multiple items, specifically the last n items, from a list using negative indexing.
Get the Last n Items from a List Using Negative Indexing
In the section above, you learned how to use Python to get the last item from a list. Now, you’ll learn how to get the last n items from a Python list.
Similar to the approach above, you’ll use negative indexing to access the last number of items.
One thing that’s great about Python is that if you want your indexing to go to the end of a list, you simply do not include a number at the end of the index.
Let’s say we wanted to return the last 2 items, we could write the following code:
a_list = ['datagy', 1,[3,4,5], 14.3, 32, 3] items = a_list[-2:] print(items) #Returns: [32, 3]
Similar to the example above, we could have have written our index to be [-2:-1] . However, omitting the -1 simply indicates that we want our index to go to the end of the list.
Interestingly, when slicing multiple items, even when they don’t exist, the whole list will be returned. For example, we shown below that slicing from the item -10 to the end doesn’t raise an error, but it also just omits the items that don’t exist.
a_list = ['datagy', 1,[3,4,5], 14.3, 32, 3] items = a_list[-10:] print(items) #Returns: ['datagy', 1, [3, 4, 5], 14.3, 32, 3]
In the next section, you’ll learn how to get the last item form a Python list and remove it.
PyTorch Activation Functions for Deep Learning
Activation functions play a vital role in the realm of deep learning. They’re like the secret sauce that adds flavor and complexity to our neural networks. Think of them as the superheroes that bring life to our models, enabling them to learn intricate patterns and make mind-blowing predictions. Neural networks are all about making connections… Read More » PyTorch Activation Functions for Deep Learning
How to Get the Last Item From a Python List and Remove It
Python has a built-in method, the .pop() method, that let’s you use Python to get the last item from a list and remove it from that list. This can be helpful for many different items, such as game development and more.
Let’s take a look at how we can make this happen in practise:
a_list = ['datagy', 1,[3,4,5], 14.3, 32, 3] last_item = a_list.pop() print(f'') print(f'') # Returns: # a_list=['datagy', 1, [3, 4, 5], 14.3, 32] # last_item=3
You can see here that when we print out the list following applying the .pop() method, that the last item has been removed. Furthermore, it has been assigned to the variable last_item .
Tip! We’ve used some f-string formatting here to print out both the variable name and the variable contents simultaneously. Learn more about how to do this in my tutorial here (requires Python 3.8+).
How to get last items of a list in Python?
I need the last 9 numbers of a list and I’m sure there is a way to do it with slicing, but I can’t seem to get it. I can get the first 9 like this:
5 Answers 5
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]
Note that -0 is 0 . So a[-0:] returns whole a , not the last zero elements [] . For guarding zero, you can use a[-n:] if n > 0 else [] .
a negative index will count from the end of the list, so:
Slicing
Python slicing is an incredibly fast operation, and it’s a handy way to quickly access parts of your data.
Slice notation to get the last nine elements from a list (or any other sequence that supports it, like a string) would look like this:
When I see this, I read the part in the brackets as «9th from the end, to the end.» (Actually, I abbreviate it mentally as «-9, on»)
Explanation:
But the colon is what tells Python you’re giving it a slice and not a regular index. That’s why the idiomatic way of copying lists in Python 2 is
And clearing them is with:
(Lists get list.copy and list.clear in Python 3.)
Give your slices a descriptive name!
You may find it useful to separate forming the slice from passing it to the list.__getitem__ method (that’s what the square brackets do). Even if you’re not new to it, it keeps your code more readable so that others that may have to read your code can more readily understand what you’re doing.
However, you can’t just assign some integers separated by colons to a variable. You need to use the slice object:
last_nine_slice = slice(-9, None)
The second argument, None , is required, so that the first argument is interpreted as the start argument otherwise it would be the stop argument.
You can then pass the slice object to your sequence:
>>> list(range(100))[last_nine_slice] [91, 92, 93, 94, 95, 96, 97, 98, 99]
islice
islice from the itertools module is another possibly performant way to get this. islice doesn’t take negative arguments, so ideally your iterable has a __reversed__ special method — which list does have — so you must first pass your list (or iterable with __reversed__ ) to reversed .
>>> from itertools import islice >>> islice(reversed(range(100)), 0, 9)
islice allows for lazy evaluation of the data pipeline, so to materialize the data, pass it to a constructor (like list ):
>>> list(islice(reversed(range(100)), 0, 9)) [99, 98, 97, 96, 95, 94, 93, 92, 91]
The last 9 elements can be read from left to right using numlist[-9:], or from right to left using numlist[:-10:-1], as you want.
>>> a=range(17) >>> print a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] >>> print a[-9:] [8, 9, 10, 11, 12, 13, 14, 15, 16] >>> print a[:-10:-1] [16, 15, 14, 13, 12, 11, 10, 9, 8]
Here are several options for getting the «tail» items of an iterable:
n = 9 iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
We get the latter output using any of the following options:
from collections import deque import itertools import more_itertools # A: Slicing iterable[-n:] # B: Implement an itertools recipe def tail(n, iterable): """Return an iterator over the last *n* items of *iterable*. >>> t = tail(3, 'ABCDEFG') >>> list(t) ['E', 'F', 'G'] """ return iter(deque(iterable, maxlen=n)) list(tail(n, iterable)) # C: Use an implemented recipe, via more_itertools list(more_itertools.tail(n, iterable)) # D: islice, via itertools list(itertools.islice(iterable, len(iterable)-n, None)) # E: Negative islice, via more_itertools list(more_itertools.islice_extended(iterable, -n, None))
- A. Traditional Python slicing is inherent to the language. This option works with sequences such as strings, lists and tuples. However, this kind of slicing does not work on iterators, e.g. iter(iterable) .
- B. An itertools recipe. It is generalized to work on any iterable and resolves the iterator issue in the last solution. This recipe must be implemented manually as it is not officially included in the itertools module.
- C. Many recipes, including the latter tool (B), have been conveniently implemented in third party packages. Installing and importing these these libraries obviates manual implementation. One of these libraries is called more_itertools (install via > pip install more-itertools ); see more_itertools.tail .
- D. A member of the itertools library. Note, itertools.islice does not support negative slicing.
- E. Another tool is implemented in more_itertools that generalizes itertools.islice to support negative slicing; see more_itertools.islice_extended .
It depends. In most cases, slicing (option A, as mentioned in other answers) is most simple option as it built into the language and supports most iterable types. For more general iterators, use any of the remaining options. Note, options C and E require installing a third-party library, which some users may find useful.