Home > database >  Weird behaviour of loops in python
Weird behaviour of loops in python

Time:02-08

So I was trying to do some basic stuff list stuff in a different way, and I came across weird behaviour in this code. I'm not sure if its a compiler/machine dependent result and I can't even google this because I'm just so lost.

Here is the code:

import random

L = (int(input("For List 1, enter a number: ")) for i in range(random.randint(2, 5)))
L1 = (int(input("For List 2, enter a number: ")) for i in range(random.randint(2, 6)))

common = []

for i in L:
  if i in L1:
    common.append(i)

print(common)

From my limited understanding, line 3 and 5 should have just resulted in L and L1 having the last entered integer stored in them, but when I execute the program it just flits between line 3 and 5. Furthermore, if I try to print L and L1 it just prints its object type (genexpr) and location in memory, before the prompts for inputs. Why is the code behaving that way?

CodePudding user response:

I think what you want to do is to use a list comprehension with square brackets instead of curved brackets.

import random

L = [int(input("For List 1, enter a number: ")) for i in range(random.randint(2, 5))]
L1 = [int(input("For List 2, enter a number: ")) for i in range(random.randint(2, 6))]
common = []

for i in L:
  if i in L1:
    common.append(i)

print(common)

If you instead want to do a tuple comprehension, you could do it as follows:

import random

L = tuple(int(input("For List 1, enter a number: ")) for i in range(random.randint(2, 5)))
L1 = tuple(int(input("For List 2, enter a number: ")) for i in range(random.randint(2, 6)))
common = []

for i in L:
  if i in L1:
    common.append(i)

print(common)

CodePudding user response:

I don't exactly understand your problem description ("it just flits between line 3 and 5"??), but the unexpected bahavior is probably caused by the generator expressions which you are using, which are evaluated lazily.

This means that the values for L and L1 will be generated as needed, one value at a time, in each iteration of the for loop(s).

Since you are using nested loops, for each value generated for L a value will be generated for L1.

To avoid the lazy evaluation, use lists instead of generator expressions, i.e.

L = [int(input("For List 1, enter a number: ")) for i in range(random.randint(2, 5))]
L1 = [int(input("For List 2, enter a number: ")) for i in range(random.randint(2, 6))]
  •  Tags:  
  • Related