I'm fairly new to coding. I'm trying to create 2 unique lists, so that l2 never has the same value in the same index of l1. Basically, the if statement works well to check if a (the random value) is not already in l2, but doesn't work when it comes to check if a is the same value as l1 for the same index. I'll then scale this code to make a Sudoku game with 9 lists, each having 9 elements.
l1 = [1, 2, 3, 4]
l2 = []
i = 0
while len(l2) < 4:
a = random.randrange(1, 5)
if a not in l2 or not l1[i]:
l2.append(a)
i += 1
print(l1, l2)
Welcome to StackOverflow! Currently you are doing the checking wrongly. if a not in l2 or not l1[i]
checks for 2 things:
l2
does not contains a
ORl1[i]
is not 0 (because l1[i]
is checked as a boolean
, and not 0
= 1
, which is true
)You have to use this check instead if a not in l2 and a != l1[i]
, which checks for:
l2
does not contains a
ANDl1[i]
does not equal to the value of a
There are more efficient ways to do this, but since you are fairly new to coding I don't want to suggest an overly complicated solution yet as that wouldn't be helpful to learning.
Also, do you want the condition to be an and or an or? that might be your problem, without realizing it
l1 = [1, 2, 3, 4]
l2 = []
while len(l2) < 4:
a = random.randrange(1, 5)
length_l2 =
if a not in l2 and a != l1[len(l2)]:
l2.append(a)
print(l1, l2)
Instead of using I, you can just use the length of l2 and then check that spot in l1, because if the length of l2 is 3 items [2, 1, 4] and you want to check to see if a is equal to the item that is in the 4th spot of l1, the index would be 3 as indices go 0, 1, 2, 3, so the length works perfectly.
Not sure if you know about sets, but sets ensure that you don't have repeated items, so it could be good practice to use some sets in this code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With