Python Forum

Full Version: Remove elements from lists
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I have some lists:
sp_0 = [1, 0, 3, 395, 399]
sp_1 = [1, 96, 11, 398]
sp_2 = [1, 0, 3, 10, 397]
sp_3 = [1, 0, 96, 130, 396]
sp_4 = [1, 0, 3, 395]

I need that the 1st elements will be removed (each time) in all lists if they are the same

Here are the iterations:
sp_0 = [1, 0, 3, 395, 399] => [0, 3, 395, 399] => [3, 395, 399]
sp_1 = [1, 96, 11, 398] => [96, 11, 398]
sp_2 = [1, 0, 3, 10, 397] => [0, 3, 10, 397] => [3, 10, 397]
sp_3 = [1, 0, 96, 130, 396] => [0, 96, 130, 396] => [96, 130, 396]
sp_4 = [1, 0, 3, 395] => [0, 3, 395] => [3, 395]

The red lists are the final results, how can I code this in less loops ?

Thanks
I understand why the "1" disappeared, why did the "0"s disappear? They're not a first element of a list?
(Jun-20-2020, 07:35 PM)bowlofred Wrote: [ -> ]I understand why the "1" disappeared, why did the "0"s disappear? They're not a first element of a list?

Thank you bowlofred, you're right, I didn't choose the right example

I edited the example
You can't do it in a single pass since you don't know until you look at the last list if you might have had to remove elements from earlier lists. So it'll take two loops. I'd use a Counter to track the leading elements, then loop over the lists and remove any that are above your limit.

from collections import Counter

def trim_lists(all_lists):
    """Modifies the passed lists to remove leading elements that are 
    found in more than one list"""
    itemcount = Counter((x[0] for x in all_lists))
    for mylist in all_lists:
        if itemcount[mylist[0]] > 1:
            mylist.pop(0)

sp_0 = [1, 0, 3, 395, 399]
sp_1 = [1, 11, 398]
sp_2 = [1, 0, 3, 10, 397]
sp_3 = [1, 0, 96, 130, 396]
sp_4 = [1, 0, 3, 395]
all_lists = [sp_0, sp_1, sp_2, sp_3, sp_4]

trim_lists(all_lists)  # trim the 1's
trim_lists(all_lists)  # trim the 0's

print(all_lists)
Output:
[[3, 395, 399], [11, 398], [3, 10, 397], [96, 130, 396], [3, 395]]
Thank you