Why am I receiving an error when trying to compare two lists?
<p>I am trying to compare two lists on line <code>#12</code> and return matches found. </p>

<p>The lists contain one user selected number (<code>un</code>) and one of which have been randomly generated (<code>rn</code>).</p>

<p>For example, <code>[['1', '5', '3', '7']]</code> and <code>[['9', '6', '3', '2']]</code> would return <code>[3]</code>.</p>

<p>I am fairly new to python and was using the solution found <a href="http://stackoverflow.com/questions/1388818/how-can-i-compare-two-lists-in-python-and-return-matches">HERE</a>, but am yet to have success with my code.</p>

<pre><code>import random
import re

rn = []
un = []

Numbers = range(1000,9999)
RandomNumber = random.choice(Numbers)
RandomNumber = str(RandomNumber)

def check():
    x = set(rn) &amp; set(un) #12
    print (x)

def numsys():
    b = list(RandomNumber)
    rn.append(b)
    print(rn)
    print(un)
    check()


def numval():
    while True:
        UserNum = (input("Please enter a 4 digit number: "))
        if re.match("^[0-9]{4,4}$", UserNum):
            a = list(UserNum)
            un.append(a)
            numsys()
            break        
numval()
</code></pre>

<p>Rather than using lists to pass the data around, use function parameters.</p>

<pre><code>import random
import re

def check(random_number, user_number):
    print('random_number {}, user_number {}'.format(random_number, user_number))
    x = set(random_number).intersection(user_number)
    print(x)

def numval():
    random_num = str(random.choice(range(1000, 9999)))
    while True:
        user_num = (input("Please enter a 4 digit number: "))
        if re.match("^[0-9]{4,4}$", user_num):
            check(random_num, user_num)
            break

numval()
</code></pre>

<p>This avoids accessing global variables within the functions and is generally more readable. Doing this I was able to remove function <code>numsys()</code> because all it was doing was to unnecessarily fiddle with the global variables in order to make their values accessible in function <code>check()</code>.</p>

<p>One simplification was to keep the random and user numbers as strings. <code>set()</code> can be called on a string without requiring that it be first converted to a list. And only one of the strings needs to be explicitly converted to a set if you use <code>set.intersection()</code> instead of the <code>&amp;</code> operator.</p>

<p>I also took the liberty of renaming the variables to conform with the <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP8 style guide</a>.</p>

python list python-3.x string-comparison list-comparison