Discussions

python - How do I get the last element of a list? - Stack Overflow
How do I get the last element of a list in Python? I tried: alist[::-1] but I got ValueError: attempt to assign sequence of size 6 to extended slice of size 5 More on stackoverflow.com
๐ŸŒ stackoverflow.com
python 3.x - i want to find the second last element in the list - Stack Overflow
Releases Keep up-to-date on features we add to Stack Overflow and Stack Internal. ... pythonjavascriptc#reactjsjavaandroidhtmlflutterc++node.jstypescriptcssrphpangularnext.jsspring-bootmachine-learningsqlexceliosazuredocker More on stackoverflow.com
๐ŸŒ stackoverflow.com
-1 returns second to last item in python list - Stack Overflow
Stack Overflow chat opening up to all users in January; Stack Exchange chat... 55 How to treat the last element in list differently in Python? 2 Why does print my_list[10:0:-1] stop with the second item rather than the first item in Python? More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Find the second last number from a list - Stack Overflow
Releases Keep up-to-date on features we add to Stack Overflow and Stack Internal. ... Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... def get_second... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Find elsewhere
๐ŸŒ
ItSolutionstuff
itsolutionstuff.com โ€บ post โ€บ python-get-second-last-element-of-list-exampleexample.html
Python Get Second Last Element of List Example - ItSolutionstuff.com
October 30, 2023 - Then I will get second last element with name using -2 key of array. so let's see the below example. You can use these examples with python3 (Python 3) version. ... myList = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] # Get Last Element ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ looping until the second to last element in a list, what's best practice?
r/learnpython on Reddit: Looping until the second to last element in a list, what's best practice?
January 11, 2024 -

edit: forgot to mention I want the indeces not just the items

the methods I can think of are:

for i in range(len(arr) - 1)

for i, e in enumerate(arr[:len(arr) - 1])

I know range(len(arr)) is frowned upon, but I don't see how it's worse than enumerate in this case. In fact using enumerate on a shortened list and calling len to find the second to last element of that list seems extremely clunky and far less readable.

What's the best practice for doing this?

๐ŸŒ
Stack Abuse
stackabuse.com โ€บ python-get-last-element-in-list
Python: Get Last Element in List
March 2, 2023 - lastElement = exampleList[-1] print("Last element: ", lastElement) print("exampleList: ", exampleList) secondToLast = exampleList[-2] print("Second to last element: ", secondToLast) ... Negative indexing does not change the original list. It is only a way of accessing elements without any changes ...
๐ŸŒ
Hyperskill
hyperskill.org โ€บ university โ€บ python โ€บ pop-in-python
Pop() in Python
October 14, 2025 - Negative indices allow access to elements from the end of the list. For example, my_list.pop(-1) removes and returns the last item, while my_list.pop(-2) removes and returns the second last item.
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ python โ€บ get last element of list in python
How to Get Last Element of List in Python | Delft Stack
February 15, 2024 - If we do not want to remove the last element from the list, we have to use -1 as the list index. In Python, the -1 index means the last index. Similarly, the -2 index indicates the second last index and so on.
Top answer
1 of 5
8

An itertools approach with the building blocks broken out - get last elements, group into threes, convert groups of 3 into a list...

from operator import itemgetter
from itertools import imap, izip

last_element = imap(itemgetter(-1), a)
in_threes = izip(*[iter(last_element)] * 3)
res = map(list, in_threes)
# [[0, 3, 1], [2, 5, 2], [1, 2, 0], [0, 4, 2]]

However, it looks like you want to "group" on the first element (instead of purely blocks of 3 consecutive items), so you can use defaultdict for this:

from collections import defaultdict
dd = defaultdict(list)
for el in a:
    dd[el[0]].append(el[-1])

# defaultdict(<type 'list'>, {100: [0, 3, 1], 101: [2, 5, 2], 102: [1, 2, 0], 103: [0, 4, 2]})
2 of 5
2

You are trying to do two things here:

  • Get the last element of each nested list.
  • Group those elements by the first element of each nested list.

You can use list comprehension to get the last element of each nested list:

last_elems = [sublist[-1] for sublist in outerlist]

If the whole list is sorted by the first element (the id) then you can use itertools.groupby to do the second part:

from itertools import groupby
from operator import itemgetter

[[g[-1] for g in group] for id_, group in groupby(outerlist, key=itemgetter(0))]

Demo:

>>> outerlist = [
...     [100,'XHS',0],
...     [100,'34B',3],
...     [100,'42F',1],
...     [101,'XHS',2],
...     [101,'34B',5],
...     [101,'42F',2],
...     [102,'XHS',1],
...     [102,'34B',2],
...     [102,'42F',0],
...     [103,'XHS',0],
...     [103,'34B',4],
...     [103,'42F',2]
... ]
>>> from itertools import groupby
>>> from operator import itemgetter
>>> [[g[-1] for g in group] for id_, group in groupby(outerlist, key=itemgetter(0))]
[[0, 3, 1], [2, 5, 2], [1, 2, 0], [0, 4, 2]]

If it wasn't sorted, you'd either have to sort it first (using outerlist.sort(key=itemgetter)), or, if you don't need a sorted version anywhere else, use a collections.defaultdict approach to grouping:

from collections import defaultdict

grouped = defaultdict(list)
for sublist in outerlist:
    grouped[sublist[0]].append(sublist[-1])

output = grouped.values()
Top answer
1 of 2
2

It's simply a matter of iterating over the list and reporting list[n-1] when list[n]>my_limit.

You will need to extend this to cope with edge cases (i.e. this will error if the first value is over the limit etc.)

And you might want to split your list into one list per commodity as this will trigger when commodities change too.

my_limit = 0.2

for n in range(1, len(my_list)):
    value = float(my_list[n][2].replace(",", "."))
    prev_value = float(my_list[n-1][2].replace(",", "."))

    if value > my_limit and prev_value < my_limit:
        print(my_list[n-1])
2 of 2
1

you can use the itertools module for this

>>> import itertools
>>> my_list = [
    ['Morocco', 'Fish', '0,012'],
    ['Morocco', 'Fish', '0,153'],
    ['Morocco', 'Fish', '0,114'],
    ['Morocco', 'Fish', '0,109'],
    ['Morocco', 'Fish', '0,252'],
    ['Spain', 'Fish', '0,012'],
    ['Spain', 'Fish', '0,113'],
    ['Spain', 'Fish', '0,116'],
    ['Spain', 'Fish', '0,250'],
    ['Spain', 'Fish', '0,266'],
    ['Italy', 'Fish', '0,112'],
    ['Italy', 'Fish', '0,025'],
    ['Italy', 'Fish', '0,224'],
    ['Italy', 'Fish', '0,256'],
    ['Italy', 'Fish', '0,245']]
>>> my_limit = 0.2
>>> for key,sublists in itertools.groupby(my_list,lambda y:y[0]):
        v=[] #we initialize it in case no element fulfill the condition
        for v in itertools.takewhile(lambda x:float(x[-1].replace(",","."))<my_limit ,sublists):
            pass
        if v: 
            print(v,"->",v[-1])

    
['Morocco', 'Fish', '0,109'] -> 0,109
['Spain', 'Fish', '0,116'] -> 0,116
['Italy', 'Fish', '0,025'] -> 0,025
>>> 

here with groupby we, well, group together all the consecutive sublist that have the same value in a given position we specify, which in this case is the first position, then we go into those sublist and take those that fulfill our condition and stop at the first that doesn't with takewhile and from those we only want the last one which will stored into v at the end of the loop.

I make that grouping because that make more sense to my, but if grouping like that isn't necessary, we can also use groupby to split the list into the subsection that fulfill the condition and those that do not by changing the grouping key

>>> my_list = [
    ['Morocco', 'Fish', '0,012'],
    ['Morocco', 'Fish', '0,153'],
    ['Morocco', 'Fish', '0,114'],
    ['Morocco', 'Fish', '0,109'],
    ['Morocco', 'Fish', '0,252'],
    ['Morocco', 'Fish', '0,002'],#extra
    ['Morocco', 'Fish', '0,252'],#extra
    ['Spain', 'Fish', '0,012'],
    ['Spain', 'Fish', '0,113'],
    ['Spain', 'Fish', '0,116'],
    ['Spain', 'Fish', '0,250'],
    ['Spain', 'Fish', '0,266'],
    ['Spain', 'Fish', '0,066'], #extra
    ['Spain', 'Fish', '0,366'], #extra
    ['Italy', 'Fish', '0,112'],
    ['Italy', 'Fish', '0,025'],
    ['Italy', 'Fish', '0,224'],
    ['Italy', 'Fish', '0,256'],
    ['Italy', 'Fish', '0,245'],
    ['Italy', 'Fish', '0,005'],#extra
    ['Italy', 'Fish', '0,305']]#extra
>>> for condition,sublist in itertools.groupby(my_list,lambda x:float(x[-1].replace(",","."))<my_limit):
        if condition:
            for v in sublist:
                pass
            print(v,"->",v[-1])

        
['Morocco', 'Fish', '0,109'] -> 0,109
['Morocco', 'Fish', '0,002'] -> 0,002
['Spain', 'Fish', '0,116'] -> 0,116
['Spain', 'Fish', '0,066'] -> 0,066
['Italy', 'Fish', '0,025'] -> 0,025
['Italy', 'Fish', '0,005'] -> 0,005
>>>    
๐ŸŒ
Filo
askfilo.com โ€บ cbse โ€บ smart solutions โ€บ second to last element of the list
Second to last element of the list... | Filo
May 20, 2025 - To find the second-to-last element of a list, we can use indexing techniques. In many programming languages, such as Python, negative indexing allows us to access elements from the end of the list.