Why does list comprehension not filter out duplicates?

I have a workaround to the next question. This workaround would be a for loop with a test for inclusion in the output, as shown below:

#!/usr/bin/env python

def rem_dup(dup_list):
    reduced_list = []
    for val in dup_list:
        if val in reduced_list:
            continue
        else:
            reduced_list.append(val)

    return reduced_list

I ask the following question because I am interested to know if there is a solution for understanding the list.

Given the following data:

reduced_vals = []
vals = [1, 2, 3, 3, 2, 2, 4, 5, 5, 0, 0]

Why

reduced_vals = = [x for x in vals if x not in reduced_vals]

create the same list?

>>> reduced_vals
[1, 2, 3, 3, 2, 2, 4, 5, 5, 0, 0]

I think this has something to do with checking the output ( reduced_vals) as part of the destination of the list. I'm curious, though for what reason.

Thank.

+5
source share
5 answers

Understanding the list creates a new list, and reduced_valsalways points to an empty list when evaluating the understanding of the list.

Python: . - .

, set() collections.OrderedDict.fromkeys() ( , ).

+6

.

, reduced_vals, , .

, [x for x in vals if x not in reduced_vals] . , :

temp_var = [x for x in vals if x not in reduced_vals]
reduced_vals = temp_var
del temp_var

reduced_vals, .

+4

: [x for x in vals if x not in reduced_vals] , reduced_vals, reduced_vals - []. , , vals .

:

[x for x in vals if x in reduced_vals]

[], reduced_vals ( ). , , : , , True, .

, , . - , :

vals = [1, 2, 3, 3, 2, 2, 4, 5, 5, 0, 0]
list(set(vals))
> [0, 1, 2, 3, 4, 5]
+4
source

Because the elements in the list comprehension are not tied to reduced_vals, until the entire list is created. Use a loop forwith .append()if you want to do this job.

+1
source

Because it reduced_valsdoes not change during the assessment of the understanding of the list.

0
source

All Articles