Home > Software design >  How to create lists using for loop in pyhton
How to create lists using for loop in pyhton

Time:12-03

What I want to get is

[a][b][c]

Getting each index from an array a=[a,b,c]. I’m using this to approach a value in dictionary.

All I could find was .append() but this returns me [a,b,c] not [a][b][c]

This is the function that I made

Def loop():
   Newlist = []
   for i in a:
      Newlist.append(i)
   return Newlist
     

CodePudding user response:

You want to append a list of one value, not a single value. i.e.

>>> new_list = []
>>> new_list.append([1])
>>> new_list.append([2])
>>> new_list.append([3])
[[1], [2], [3]]

So in the method you'd do something like this:

def loop():
    new_list = []
    for i in a:
        new_list.append([i])
    return new_list

CodePudding user response:

Try this:

Create a new list inside the loop that gets reset each time, add your variable, then add the new list to the parent list.

You can also grab individual lists from the parent list using the following: Newlist[1]

Def loop():
   Newlist = []
   for i in a:
      temp_list = []
      temp_list.append(I)
      Newlist.append(temp_list)
   return Newlist
  • Related