1

I am trying to create new list_names during an Iteration that I can add Elements to.

# input
df = pd.DataFrame({"R1": [8,2,3], "R2": [-21,-24,4], "R3": [-9,46,6]})

input

# desired Output
list1 = df.values[0].tolist()
print(list1)
list2 = df.values[1].tolist()
print(list2)
list3 = df.values[2].tolist()
print(list3)

desired output

# failed attempt
for i in range(3):
    print(f'{"list"}{i}') = df.values[i].tolist()

failed attempt

  • 1
    No. Two issues: First, iteration on dataframes is an antipattern, and should be almost always avoided. Second, you're effectively asking how to make a dynamic number of variables on the fly. It's better to actually make a list/dict instead. – Paritosh Singh Aug 21 '19 at 09:12
  • You're assigning a value to a function call, what does `f() = x` mean? – Zain Patel Aug 21 '19 at 09:13
  • I am sorry to ask, but which function are you referring to? – Dieter Mueller Aug 21 '19 at 09:17
  • related: https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables – Paritosh Singh Aug 21 '19 at 09:23
  • 1
    Don't try to create variables `list1`, `list2`, etc. Python (and other languages) has list and dictionary to keep many results - `result["1"] = ...`, `result["2"] = ...` – furas Aug 21 '19 at 09:23

3 Answers3

5

You can work on the entire dataframe without iteration. Access the underlying array and convert it into a list of lists in one go.

import pandas as pd
df = pd.DataFrame({"R1": [8,2,3], "R2": [-21,-24,4], "R3": [-9,46,6]})

#out = df.to_numpy().tolist() for pandas >0.24
out = df.values.tolist()
print(out)
print(out[0])
print(out[1])
print(out[2])

Output:

[[8, -21, -9], [2, -24, 46], [3, 4, 6]]
[8, -21, -9]
[2, -24, 46]
[3, 4, 6]

In this manner, you can use the out variable as a collection of all individual lists that you wanted.


If you wish to use a dictionary instead, you can also create that as follows:

out_dict = {f"list{i}":lst for i, lst in enumerate(out, start=1)}
#Output:
{'list1': [8, -21, -9], 'list2': [2, -24, 46], 'list3': [3, 4, 6]}

print(out_dict['list1'])
print(out_dict['list2'])
print(out_dict['list3'])

Between the list and dict approaches, you should be able to cover all use-cases you really need. It is generally a bad idea to try making a variable number of variables on the fly. Related read

Paritosh Singh
  • 6,034
  • 2
  • 14
  • 33
1
for i in range(3):
    print('list{} = {}'.format(i, df.loc[i].values.tolist()))

Output

list0 = [8, -21, -9]
list1 = [2, -24, 46]
list2 = [3, 4, 6]
ComplicatedPhenomenon
  • 4,055
  • 2
  • 18
  • 45
0

First, to answer your question, to dynamically create variables you can use exec()

for i in range(3):
    exec("List%d=%s" % (i,df.values[i].tolist()))
print(List1)

Secondly, above is a bad practise. This poses a security risk when the values are provided by external data (user input, a file or anything). So it's better avoid using it.

You can always use dictionary in that you can use key value pairs to achieve the same objective (See other answers).

j23
  • 3,139
  • 1
  • 6
  • 13
  • 1
    Please do not recommend bad programming practices, there's almost always a better way. – Paritosh Singh Aug 21 '19 at 09:21
  • Yay! That one works very well for me :-) Can you please explain what you did? – Dieter Mueller Aug 21 '19 at 09:23
  • @Paritosh Singh - What do you mean by that? Is it not recommended to do it this way? – Dieter Mueller Aug 21 '19 at 09:24
  • @DieterMueller you have list and directory to keep many results. This is recomended way in Python and other languages. – furas Aug 21 '19 at 09:25
  • @DieterMueller yeah, `exec` and `eval` are best avoided. further read [here](https://stackoverflow.com/questions/21553641/python-is-exec-always-bad-practice-and-if-so-why-not-deprecated) and [here](http://stupidpythonideas.blogspot.com/2013/05/why-evalexec-is-bad.html) – Paritosh Singh Aug 21 '19 at 09:26
  • @ParitoshSingh this is the only way I know to create dynamic variables. That was the question right? Yeah, I mentioned it as bad practise. Is there any other safe way to dynamically create variables? If yes, please do provide some examples. – j23 Aug 21 '19 at 09:29
  • 1
    The question was that. yes. But that is an XY problem. The answer should have been "please don't. Here's a cleaner way". Or if you really wish to showcase this, please highlight that this is *almost always a bad idea* in the answer itself – Paritosh Singh Aug 21 '19 at 09:31
  • 1
    @ParitoshSingh Thank you. I have updated the answer and highlighted as you suggested. – j23 Aug 21 '19 at 09:43