Python Forum
Using randomly generated lists
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using randomly generated lists
#1
Hello

I am currently writing a piece of code that creates a list from the numbers that 2 other lists have in common (excluding duplicates).
It was nice and simple when I input actual lists to use.
e.g. 2 lists of [1,1,2,3] and [1,3,4] would makes a list of just [1,3]

However, now that the lists are randomly generated, it returns an empty list as if they have no numbers in common.
Code below

import random

a = [random.sample(range(1,100), 50)] 
b = [random.sample(range(1,100), 50)]
y=[]
for i in a:
	if i in y:
		continue
	for l in b:
		if i == l:
			y = y + [i]
print(y)
Thanks for the help!

Soup
Reply
#2
Sets from set theory should be used.

a = set(a)
b = set(b)
c = a & b # unique values in a and b
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
Did you check content of a and b in your code? List a contains another list, not numbers!
Just remove square brackets in lines, where a and b are defined.
Reply
#4
(Apr-19-2019, 11:16 AM)scidam Wrote: Did you check content of a and b in your code? List a contains another list, not numbers!
Just remove square brackets in lines, where a and b are defined.

Ah yes I see, haha thank you, such a tiny thing!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Randomly generate an even number Truman 17 7,929 Apr-19-2019, 01:47 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020