0

How would I get the last three elements of a list, not including the first element?

For example, with these two lists

a = ['Matt', '1', '2'] , b = ['Luke', '1', '2', '3']

I would want the returned lists to be: ['1', '2'] and ['1', '2', '3']. Is there an easy way to do this?

kmario23
  • 57,311
  • 13
  • 161
  • 150
Matt
  • 43
  • 1
  • 2
  • 2
    How is `['1', '2']` the *last 3 elements* ? – Idos Mar 16 '16 at 12:50
  • It's the last three elements not including the first element. All the lists are in the format `['name', 'score', 'score'..]` and I need the last three 'score' elements, not including 'name'. – Matt Mar 16 '16 at 12:51

5 Answers5

1

You can simply use slicing for this:

>>> b[-3:]
['1', '2', '3']

If you have less than 3 scores in your list then you can:

>>> b = ['Luke', '1', '2']
>>> b[1:]
['1', '2']

So to combine them you can use:

if len(b) > 3:
    b[-3:]
else:
    b[1:]
Community
  • 1
  • 1
Idos
  • 15,053
  • 14
  • 60
  • 75
  • But that returns all the elements after the first. If I have a list in this format: `['n', '1', '2', '3', '4', '5'], I need it to return ['3', '4', '5'], not ['1', '2', '3', '4', '5']. – Matt Mar 16 '16 at 12:54
  • I fixed this @Matt – Idos Mar 16 '16 at 12:59
1

In order to get the last n elements from a list, you do:

a[-n:]

Here's a quick example:

>>> a = [1, 2, 3, 4]
>>> a[-3:]
[2, 3, 4]

If your list contains < n elements, you can just slice the first element out.

Maroun
  • 94,125
  • 30
  • 188
  • 241
1

In your case name is always first parameter in lists, so just apply on each of one of them:

 a = a[1:]
 b = b[1:]

Getting last three parameters won't work on a, since it contains 3 parameters. It will work after some condition statements.

If you're sure you want last 3 parameters use this:

a = a[-3:]
b = b[-3:]

Full snippet for you:

def get_list(my_list):
    if len(my_list) > 3:
        return my_list[-3:]
    else:
        return my_list[1:]
PatNowak
  • 5,721
  • 1
  • 25
  • 31
1

In addition to other good answers, you may want to consider using dictionaries instead of lists for this. You can do it like so:

a = ['Matt', '1', '2']
b = ['Luke', '1', '2', '3']
scoresDict = {}

scoresDict[a[0]] = a[1:]
scoresDict[b[0]] = b[1:]

print(scoresDict)
print(scoresDict['Matt'])
print(scoresDict['Luke'])

Output:

{'Matt': ['1', '2'], 'Luke': ['1', '2', '3']}
['1', '2']
['1', '2', '3']
Igor
  • 1,212
  • 12
  • 23
0

For varying elements in the list, put all of those in a list and map it to a lambda function.

In [1]: a = [1,2,3,4]
In [2]: b = ['a', 'b', 'c', 'd', 'e']
In [3]: lis = [a, b]

In [4]: list(map(lambda x: x[-(len(x)-1):], lis))
Out[4]: [[2, 3, 4], ['b', 'c', 'd', 'e']]
kmario23
  • 57,311
  • 13
  • 161
  • 150