1

I am currently experimenting with lists in python and am trying to create a program that will simulate the name game (click here for refrence).

The program asks for user input and generates a list with each letter of the user's name. However, it then has to generate 3 new names, each beginning with "b", "f", "m". This is where I run into a problem. When appending to master_list, and later printing my result I get the output:

[['m', 'o', 'b', 'e', 'r', 't'], ['m', 'o', 'b', 'e', 'r', 't'], 
['m', 'o', 'b', 'e', 'r', 't']]

When user input = "Robert"

Heres my code:

# Asks for user name
user_name = input("Enter name here: ")
name = list(user_name)

# Create an empty list that will contain a subsets of lists.
master_list = []

# List containing the first letter of each new name
beginning_of_word = ["b", "f", "m"]

# Creates 3 new names and appends them to master_list
for var in beginning_of_word:
    new_list = name
    new_list.pop(0)
    new_list.insert(0, var)
    print(new_list)
    master_list.append(new_list)
    if new_list != name:
        new_list = name

The intended output when master_list is printed should be:

[['b', 'o', 'b', 'e', 'r', 't'], ['f', 'o', 'b', 'e', 'r', 't'], 
['m', 'o', 'b', 'e', 'r', 't']]

Does anyone have ideas as to why this is happening?

1 Answers1

2

Although you named your variable new_list, the fact is you were operating on the same old list each time. To modify a list, and retain the original, you need to copy the list:

# Asks for user name
user_name = input("Enter name here: ")
name = list(user_name)

# Create an empty list that will contain a subsets of lists.
master_list = []

# List containing the first letter of each new name
beginning_of_word = ["b", "f", "m"]

# Creates 3 new names and appends them to master_list
for var in beginning_of_word:
    new_list = list(name)  # a copy of 'name'
    new_list[0] = var
    master_list.append(new_list)

print(master_list)

OUTPUT

% python3 test.py
Enter name here: Robert
[['b', 'o', 'b', 'e', 'r', 't'], ['f', 'o', 'b', 'e', 'r', 't'], ['m', 'o', 'b', 'e', 'r', 't']]
%
cdlane
  • 40,441
  • 5
  • 32
  • 81