Home > Back-end >  append lists in for loop
append lists in for loop

Time:11-24

I am trying to manipulate my list through the append function.

Here is what i got:

list_all = []
list_gen = ['male', 'DEAN', 'SAM', 'JASON']
list_all.append(list_gen)
list_gen = ['female', 'LARA', 'SUSI']
list_all.append(list_gen)

a_list = []
b_list = []

for x in list_all:
    a_list.append(x[:1])
    a_list.append(x[1:])
    b_list.append(a_list)
    a_list.clear()

print(b_list)

Result: [[], []]

What i want: [[['male'], ['DEAN', 'SAM', 'JASON']], [['female'], ['LARA', 'SUSI']]]

what am i doing wrong?

CodePudding user response:

list_gen1 = ['male', 'DEAN', 'SAM', 'JASON']
list_gen2 = ['female', 'LARA', 'SUSI']

list_gen1 = [[list_gen1[0]],[list_gen1[1:]]]
list_gen2 = [[list_gen2[0]],[list_gen2[1:]]]

list_gen3 = [list_gen1, list_gen2]

print(list_gen3)

CodePudding user response:

Your code is fine and i understand the logic you are doing with append. Let me clear your situation a little bit. Append is used to add ELEMENT to a list. If you give it a list, it adds it to the parent list as an element.

`list_all = []
list_gen = ['male', 'DEAN', 'SAM', 'JASON']
list_all.append(list_gen)
list_gen = ['female', 'LARA', 'SUSI']
list_all.append(list_gen)`

After this point, your list_all value is:

[['male', 'DEAN', 'SAM', 'JASON'], ['female', 'LARA', 'SUSI']]

This shows that list_all has two elements which are lists themselves.

Now you need to declare the a_list inside the for loop, not outside it.

b_list = []

for x in list_all:
    a_list = []
    a_list.append(x[:1])
    a_list.append(x[1:])
    b_list.append(a_list)

print(b_list)

and this will be your output:

[[['male'], ['DEAN', 'SAM', 'JASON']], [['female'], ['LARA', 'SUSI']]]
  • Related