Skip to content
Advertisement

Saving a new list from a a larger list using a loop

I have a large list, which I am pulling out every nth value from the first value up to the mth value to create new lists and I am using a for loop. My question is, how do I create a new list variable each time through the for loop?

By way of simple example, I have the list:

a=[1,2,3,4,1,2,3,4,1,2,3,4]

Which I am trying to convert to:

a1 = [1,1,1]
...
a4 = [4,4,4]

As a printed output I get what I want when I run the code

split = list(range(0,3))

for x in split:
   a_new = a[x::3]
   print(a_new)

But like I say, I want to be able to use those lists later. (I want to use the lists as columns for a dataframe).

Alternatively If there is a more elegant way to simply convert my original list to a pandas data frame with a1 being one column, a2 being the next column and so on, that would also be great.

Thank you.

Advertisement

Answer

You can create a dictionary in the for loop then convert it to a dataframe.

Try this code:

import pandas as pd

a=[1,2,3,4,1,2,3,4,1,2,3,4]

d = {}
for x in range(4):
   d['a'+str(x+1)] = a[x::4]
   
print(d, 'n')

df = pd.DataFrame(d)

print(df.to_string(index=False))

Output

{'a1': [1, 1, 1], 'a2': [2, 2, 2], 'a3': [3, 3, 3], 'a4': [4, 4, 4]}

 a1  a2  a3  a4
  1   2   3   4
  1   2   3   4
  1   2   3   4
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement