Home > Software engineering >  NESTED LISTS: This is a function that is supposed to return a single list and remove duplicates. It
NESTED LISTS: This is a function that is supposed to return a single list and remove duplicates. It

Time:07-12

The below function flatten the nested list of integers (List[List[int]]) into a single list and removes duplicates by leaving only the first occurrences.

def f2(list_of_list):
    result = []
    for inner_list in list_of_list:
        for x in inner_list:
            for x not in result:
                result.append(x)
    return result

If I had my list as:

leist=[[0,1,2,2,3],[3,4]]

And then apply my function to the list

f2(leist) 

I should get output: [0, 1, 2, 3, 4]

This code however throws a syntax error at line 5.

for x not in result:
                       ^
SyntaxError: invalid syntax

How do I solve this problem?

CodePudding user response:

@JuliusFx - try this code snippet for your reference, even you've prob. figured out your original problem.

>>> leist=[[0,1,2,2,3],[3,4]]
>>> lst = sum(leist, [])         # flatten all single-level sub-list
>>> lst
[0, 1, 2, 2, 3, 3, 4]
>>> list(dict.fromkeys(lst).keys())
[0, 1, 2, 3, 4]                  # remove all consecutive duplicates
>>> 
>>>>>> list(set(lst))            # Or can use set() 
[0, 1, 2, 3, 4]
>>> list(set([1, 2, 2, 2, 3, 3, 4, 1]))  # but Watch this! it'll remove other non-consecutive numbers too! 
[1, 2, 3, 4]

CodePudding user response:

You can use set to achieve this and convert back to list

result = set()
for inner_list in list_of_lists:
    for x in inner_list:
        result.append(x)
result = list(result)

Following your approach

def remove_duplicates(list_of_lists):
    result = []
    for inner_list in list_of_lists:
        for x in inner_list:
            if x not in result:
                result.append(x)
    return result

The if condition used to check weather x is present in list Time Consuming : O(n)

  • Related