How to append names from two separate lists to append and merge to one list

l.m.m :

I am trying to append names to an empty list that has an empty string and an empty list. I want to iterate using a for loop or a loop that will be able to through the friendsNum list and in the string parenthesis will insert a random name from peoplenames list which is i[0] then after two random names from the list called friendnames in the empty list which will be i[1] after the string, and to continue until the last list.

    import random 
    friendsNum = [("",[]),("",[]),("",[]),("",[])]
    peopleNames = ["Alvin","Danny","Maria","Lauren"]
    friendNames = ("john","matt","will","mario","wilma","shannon","mary","jordan") 

    newList = friendsNum
    tempName = ()
    temp = ()
    for i in friendsNum:
        tempName = random.sample(peopleNames,1)
        temp = random.sample(friendNames,2)
        newList = i[0].append(tempName)
        newList = i[1].append(temp)

After this for loop iterates, it will look like this.


    friendsNum = [("Johnny",["john","matt"]),
                  ("Zach",["wilma","shannon"]),
                  ("Dawn",["mary","jordan"]),
                  ("Max",["will","john"])]

I keep getting a error of not being able to append a string object from the lines

 newList = i[0].append(tempName)
 newList = i[1].append(temp)

Am I approaching this wrong as for the loop I should be using?

The error message below

    newList = i[0].append(tempName)
AttributeError: 'str' object has no attribute 'append'
Mohit Sharma :

Your first element is empty string in friendsnum so you can not use append operation on string. Also, you cant assign values in a tuple as its immutable.

    import random 
    friendsNum = [("",[]),("",[]),("",[]),("",[])]
    peopleNames = ["Alvin","Danny","Maria","Lauren"]
    friendNames = ("john","matt","will","mario","wilma","shannon","mary","jordan") 

    newList = []
    tempName = ()
    temp = ()
    for i in friendsNum:
        tempName = random.sample(peopleNames,1)
        temp = random.sample(friendNames,2)
        i = list(i)
        i[0] = (tempName[0])
        i[1] = (temp)
        newList.append(tuple(i))

use above updated code, here is sample output

[('Danny', ['shannon', 'will']),
 ('Alvin', ['jordan', 'john']),
 ('Maria', ['mary', 'will']),
 ('Alvin', ['wilma', 'mary'])]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=19418&siteId=1