Unique list in python

  • A+
Category:Languages

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:

  1. l2 does not contains a OR
  2. l1[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:

  1. l2 does not contains a AND
  2. l1[i] does not equal to the value of a

Comment

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