0

Here i have some code for Print common item from list, and the set(). i am not getting what result variable saying.

import random
a = random.sample(range(1,30), 12)
b = random.sample(range(1,30), 16)
result = [i for i in set(a) if i in b]

what is the meaning of the following line. please explain i new to programming.

[i for i in set(a) if i in b] 
RJT
  • 59
  • 7

2 Answers2

0

The last line performs an intersection between values of a and b in a list comprehension. Only pooly executed:

First I don't see why turning a into a set. Sampling a range of integers always provides distinct values. In that case it doesn't speed processing up, it just messes with the order (which is already random...).

Then, if i in b is inefficient (not noticeable if there are only a few values) because of the linear search (b being a list)

I'd rewrite it like this:

a = random.sample(range(1,30), 12)
b = set(random.sample(range(1,30), 16))
result = [i for i in a if i in b]

or even better using set intersection method.

result = set(random.sample(range(1,30), 12)).intersection(random.sample(range(1,30), 16))

In both rewrites, we create one set, to be able to use fast lookup / intersection with the other iterable.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

It is called list comprehension, which basically doing a regular loop inside of your array, or dictionary.

A much readable code for beginner python programmer would be:

results = []
for i in set(a):
    if i in b:
        results.append(i)

You are looking onto the list(a) and keeping only those who are in both list(a) and list(b).

Mohamed Lakhal
  • 466
  • 1
  • 4
  • 11