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'
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'])]