-1

am looping big lists looking for a list of values in that big list. The bellow is a C++ tranditional way in python to find a value or a set of values, but am pretty sure that there should a better way to do it spcially using python. Any suggestions?

a better and faster way to find a list of values in another list

list_a = [1, 2, 3]
list_b = [1, 5, 4, 7, 2, 6, 8, 9]
list_resutl = []

for number_a in list_a:
    for number_b in list_b:
        if number_a == number_b:
            list_resutl.append(number_a)

print(list_resutl)
1, 2
Sipan
  • 1
  • 1

2 Answers2

1

You can use list comprehension:

list_resutl = [item for item in list_a if item in list_b]

Code:

list_a = [1, 2, 3]
list_b = [1, 5, 4, 7, 2, 6, 8, 9]

list_resutl = [item for item in list_a if item in list_b]
print(list_resutl)

Output:

[1, 2]
ScottC
  • 3,941
  • 1
  • 6
  • 20
1

You can convert each list to a set, then use set intersection.

list_result = list(set(list_a) & set(list_b))
Unmitigated
  • 76,500
  • 11
  • 62
  • 80