1

I'd like to assign the last 3 items of a list to individual variables. What I did was:

 l = ["1", "2", "3", "4", "5"]
 a, b ,c = l[-1], l[-2], l[-3]

So a = "5", b = "4" c = "3".

It works, but I'm 99% sure there's a much better way to do this. I tried various for loops, but couldn't make it work at all. So what I' m looking for is essentially just a better version of this, getting X amount of items from the end of a list.

I'm very new to programming, and my Google-Fu failed me so I decided to ask here.

EDIT:

Thanks for the answers, though I was naive enough to think my question was the solution I needed. 100% my fault for not being exact, like the page before asking a question tells you. The answers so far sure did answer what I asked, so thanks a lot for helping me, I already learned something.

What I actually wanted to do is following:

I have a big list (in reality, not in this example), I would like to have the last three items from it and add them after a string. I want to have each list item as an individual variable (maybe not the right way to say it, but as something to add to the end of a string) to add to an existing string, as such:

a = ["1", "2", "3", "4", "5"]
for i in a:
    print("something"+a[-i])

What I wanted to do is:

something + 5
something + 4
something + 3

That didn't work, unfortunately. Iterating the list from the end, but only to a certain point (in this case 3rd item from the end) is something I'd like to learn.

Maybe the question I already asked could be used to do this, obut I just can't make it work. Apologies for my first question anyway, it was terrible by all means.

PeKo
  • 25
  • 1
  • 4

3 Answers3

3

Slice starting at 3 elements from the end of the list.

 l = ["1", "2", "3", "4", "5"]
 a, b ,c = l[-3:] #a,b,c = 3,4,5
 a, b ,c = reversed(l[-3:]) #a,b,c = 5,4,3
Garrett R
  • 2,687
  • 11
  • 15
2

If you are using python3 you can use extended iterable unpacking:

In [14]: l = ["1", "2", "3", "4", "5"]

In [15]: *_, c, b, a = l

In [16]: a,b,c
Out[16]: ('5', '4', '3')

Based on your edit, if you want to get n items from the list starting at the end and perform some function on them, you can use reversed to start at the end and islice n items from the list:

In [51]: from itertools import islice

In [52]: l = ["1", "2", "3", "4", "5"]

In [53]: c, b, a =  map("something{}".format ,  islice(reversed(l), 3))

In [54]: a,b,c
Out[54]: ('something3', 'something4', 'something5')

Or using your example for loop:

In [55]: for ele in islice(reversed(l), 3):
   ....:     print("Something{}".format(ele))
   ....:     
Something5
Something4
Something3
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
0

Use negative Indexing with negative step, to get the last three elements reversed:

l = ["1", "2", "3", "4", "5"]
a,b,c = l[:-4:-1]
# a = "5", b = "4", c = "3"
Daniel
  • 42,087
  • 4
  • 55
  • 81