bucephalusII
bucephalusII

Reputation: 59

Unique list in python

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)

Upvotes: 4

Views: 252

Answers (4)

WIT
WIT

Reputation: 1083

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.

Upvotes: 3

slider
slider

Reputation: 12990

Another way to do this would be to use random.shuffle to keep shuffling l2 while any elements at the same index are equal:

import random

l1 = list(range(1, 5))
l2 = list(range(1, 5))
random.shuffle(l1)

while any(x == y for x, y in zip(l1, l2)):
    random.shuffle(l2)

print(l1)
print(l2)

Output

[1, 4, 3, 2]
[2, 3, 4, 1]

Upvotes: 2

Hayat
Hayat

Reputation: 1649

You can try this method too.

k = [1,2,3,4,5]
l= [9,8,7,6,5]
m = set(k).intersection(set(l))

It's a bit fast.

Upvotes: 0

Andreas
Andreas

Reputation: 2521

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

Upvotes: 4

Related Questions