generating random number and merge it into an older list using python

376 views Asked by At

I have a list. I am trying to generate a new list which is different from older list and merge it into older list. If generated number is already exist in older list then give an appropriate error otherwise merge both list, i.e. older list + new list,.

I written a code which gives me merge list but not appropriate result. Sample code is given below:

test.py

import random
def testfunc():
    old_list = [12, 23, 34, 45, 56]
    new_list = []
    for i in range(10, 15):
        randomnumber = int(random.randint(10, 100))
        x = new_list.append(randomnumber)
        old_list.append(x)
    print(old_list)

if __name__ == "__main__":
    testfunc()

output

[12, 23, 34, 45, 56, None, None, None, None, None]

Please help me to solve this problem and tell me appropriate condition to check the older list and newer list. Thanks in Advance.

1

There are 1 answers

3
TerryA On BEST ANSWER

The list.append() function does not return a new list, it just adds an item to the list in place. Thus, when you do x = new_list.append(randomnumber), you're actually setting x to None.

To fix this, just do new_list.append(randomnumber). That way you have two lists, the old and new one. Then you can do a later test to see if any numbers in either list match.