Vishal
Vishal

Reputation: 20627

Trimming lists using a loop

I have few lists like:

a = [1, 2, 3, 4, 5]
b = [4, 6, 5, 9, 2]
c = [4, 7, 9, 1, 2]

I want to trim all of them using a loop, instead of doing as below:

a[-2:]
b[-2:]
c[-2:]

I tried but got confused with pass by value or pass by reference fundamentals, looked into other questions as well but no help.

Thanks

Upvotes: 0

Views: 162

Answers (3)

sth
sth

Reputation: 229774

Deleting the unwanted items from the existing lists, using a loop:

for list in [a, b, c]:
   del a[:-2]

Or, creating new lists containing only the correct items, using a list comprehension:

(a, b, c) = [x[-2:] for x in (a, b, c)]

Upvotes: 1

gilesc
gilesc

Reputation: 1979

x = [a, b, c]
x = map(lambda lst: lst[-2:], x)   

Upvotes: 1

Tamás
Tamás

Reputation: 48071

for l in [a, b, c]:
    del l[-2:]

This removes the last two elements from each list. If you want to remove all but the last two elements only, do this:

for l in [a, b, c]:
    del l[:-2]

There's no need to worry about references here; the list over which the for loop iterates contains references to a, b and c, and each list is mutated in-place by deleting a list slice.

Upvotes: 4

Related Questions