Home > Net >  Python get first k elements from the list, which are present in another list
Python get first k elements from the list, which are present in another list

Time:03-25

I have a list1:

        [1, 2, 3, 4]

and another list2:

        [4, 2, 10, 20, 3, 1]

I want to take 1st 3 elements of list2, which are present in list1:

Output-list

        [4, 2, 3]

How to do this?

CodePudding user response:

you create list comprehension with a condition to check list2 in list1

list1 = [1, 2, 3, 4]
list2 = [4, 2, 10, 20, 3, 1]

output_list = [i for i in list2 if i in list1][0:3]
print(output_list)

CodePudding user response:

If order of elements doesn't matter you can use set intersection. If it does, you need to iterate over list2:

list1 = [1, 2, 3, 4]
list2 = [4, 2, 10, 20, 3, 1]

# If order of elements doesn't matter
common = set(list1).intersection(list2)
print(common)

# If order does matter
result = []
for element in list2:
    if element in list1:
        result.append(element)

    if len(result) >= 3:
        break

print(result)
  • Related