Search code examples
pythonloopsfor-loopif-statementdatatable

how to save the result from looping in python to a variable


i have a struggle to understand how to save the result of looping, i want to drop my several data in the table

for i in range(1,9):
  if i % 2 == 0:
    print(i, end=",")

The result was

2,4,6,8,

Then i copied it manually and take the result to put in the next code.

mydata.drop([ 2,4,6,8 ],axis= 0 ,inplace= True )

It worked when i input the result manually, i expect to input the result automatically, i want to save the result of looping in a variable or anything else to make it more effective


Solution

  • It sounds like you're not understanding scoping. Every variable, even i within your loop has a scope, which basically means there parts of code it is available to be read from "in scope" and the rest it is unavailable or "out of scope". This is a beginner article that might help you.

    You could have a variable outside of the loop, at the global scope for your application (described in the linked article), that holds your values and can be read and amended from anywhere in your code.

    results_list=[]
    
    for i in range(1,9):
      if i % 2 == 0:
        results_list.append(i)
        print(i, end=",")
    

    After this section of code has run the results_list will still be available for use.