-2

if i have two lists (may be with different len):

x = [1,2,3,4]
f = [1,11,22,33,44,3,4]

result = > [11, 22, 33, 44]

doing:

for element in x:
    if element in f:
        f.remove(element)

getting

result = [11,22,33,44,4]

set method return ordered collection but i need to keep order of elements.

is there better way to do that?

ali sarkhosh
  • 183
  • 1
  • 12

5 Answers5

6

Editing a list while iterating over it is bad practice, but here's a list comprehension to do what you want. This will keep the order as well.

>>> x = [1,2,3,4]
>>> f = [1,11,22,33,44,3,4]
>>> [a for a in f if a not in set(x)]
[11, 22, 33, 44]
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
2

How about set operations? This is going to generate a sorted list, which is independent to the provided order:

>>> x = [1,2,3,4]
>>> f = [1,11,22,33,44,3,4]
>>> sorted(set(f) - set(x))
[11, 22, 33, 44]
Giorgos Myrianthous
  • 36,235
  • 20
  • 134
  • 156
0

You should avoid removing elements of a list while looping through it. Making a copy helps.

x = [1,2,3,4]
f = [1, 11, 22, 33, 44, 3, 4]
f2 = f.copy()
for element in f2:
    if element in x:
        f.remove(element)

print(f)
San
  • 1
0

if you iterate the list from bottom to top, you will get the correct result:

x = [1,2,3,4]
f = [1,11,22,33,44,3,4]

for i in range(len(f)-1, -1, -1):
    if f[i] in x:
        f.pop(i)        

print(f)  # [11, 22, 33, 44]
Giannis Clipper
  • 707
  • 5
  • 9
0

try this one line code, you will get the result

x = [1, 2, 3, 4]
f = [1, 11, 22, 33, 44, 3, 4]
print(sorted(set(f).difference(set(x))))

output: [11, 22, 33, 44]
Nasreen Ustad
  • 1,564
  • 1
  • 19
  • 24