Home > Blockchain >  Loop making lists
Loop making lists

Time:12-16

I was working on a dataframe that has many countries. Trying to store each country on a list of its own

while I expected

for x in unique_countries:
    x = []
    x.append(x)
    print(x)  

to do the job, instead I got a series of ellipses. I instead changed the code to:

for x in unique_countries:
    y = x
    x = []
    x.append(y)
    print(x)

which gave me the result I wanted, but I dont understand why the first one didnt work. Very curious to know why!

CodePudding user response:

You can do it very easily with pandas. Here:

import pandas as pd 
# ...
#  your code here
# ...
col_list = df["unique_countries"].values.tolist()
print(col_list)

CodePudding user response:

x in unique_countries is your variable, your country. If you assign that variable a list, x will be overwritten by the list, and your country will be lost. With:

x.append(x)

you append to your list, the same list, and that's not what you want to achieve. Try with this:

for x in unique_countries:
    print([x])

This way, you are inserting the variable into a list by printing it directly with one statement

CodePudding user response:

In the first block of code, you are assigning x to an empty list and appending an empty list to itsels

    x = []
    x.append(x) # [].append([])

Whereas in the second block you are assigning x to y and appending y to the empty list

    y = x
    x = []
    x.append(y) # [].append(y)

Hopefully this answers your question.

An optimization for what you want is as follows.

[[x] for x in unique_countries]
  • Related