Home > other >  insert n in list x --> append list x to list y --> delete n in list x
insert n in list x --> append list x to list y --> delete n in list x

Time:11-01

I'm trying to insert the number "1" to the list in every position with a for loop and eventually get all possible lists in python.

For Example:

l = ["2","3","6"]

number = "1"

output = [["1","2","3","6"],["2","1","3","6"],["2","3","1","6"],["2","3","6","1"]]

l = ["2","3","6"]
list_of_nrs = []
for index in range(len(l) 1):
    l.insert(index, "1")
    list_of_nrs.append(l)
    del l[index]
print(list_of_nrs)

So I've tried it like the code above me, but the output I get is:

[['2', '3', '6'], ['2', '3', '6'], ['2', '3', '6'], ['2', '3', '6']] 

It seems like there is a problem between the append and del function.

CodePudding user response:

When you append the output list,you use reference value like pointers in C.Whenever change the value of it in anywhere,it change all over the program.So you have to create new list value.You can use like this:

l = ["2","3","6"]
list_of_nrs = []
for index in range(len(l) 1):
   temp = list(l) # temp is new list, it wont refer to l anymore
   temp.insert(index, "1")
   list_of_nrs.append(temp)
print(list_of_nrs)

CodePudding user response:

Your list_of_nrs contains four references to the same list that you keep repeatedly modifying; appending it to the list doesn't create a copy of it!

To create a copy, use .copy():

l = ["2", "3", "6"]
list_of_nrs = []
for index in range(len(l) 1):
    l.insert(index, "1")
    list_of_nrs.append(l.copy())  # note the .copy()!
    del l[index]
print(list_of_nrs)

prints:

[['1', '2', '3', '6'], ['2', '1', '3', '6'], ['2', '3', '1', '6'], ['2', '3', '6', '1']]

The above is the fix that makes the minimal change to your original code; for another approach entirely, you could construct new lists by slicing the original list at different points:

l = ["2", "3", "6"]
list_of_nrs = [
    l[:i]   ["1"]   l[i:]
    for i in range(len(l) 1)
]
print(list_of_nrs)
  • Related