list comprehension iterating over two lists is not working as expected

  • A+

I want to iterate over two lists the first list contains some browser user-agents and the second list contains versions of those browsers. I want to filter out only those user-agents whos version is greater than 60.

Here is how my list comprehension looks like

[link for ver in version for link in useragents if ver > 60] 

The problem with this list is that it prints same user-agent multiply time

I wrote the same thing using zip function, which works fine

for link, ver in zip(useragents, version):     if ver > 60:         # append to list         print(link) 

I cannot figure out what I've been doing wrong


Your first list comprehension is equivalent to:

res = [] for ver in version:     for link in useragents:         if ver > 60:             res.append(link) 

Notice you have nested loop with time complexity O(n2), i.e. you are iterating over every combination of version and useragents. That's not what you want, assuming your version and useragents lists are aligned.

The equivalent of your for loop is the following list comprehension:

res = [link for link, ver in zip(useragents, version) if ver > 60] 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: