0

Although it might be easy but i am not able to get a hang of it..

I want to assign the result to a new variable every time the for loop iteration occurs. I don't wish to do with initializing the list or dict and then adding the result. Because that way still it won't assign to a new variable each time.

Basically i want to automate this set of code.

data_Absen_1 = pd.read_excel('Absenteesim jan22.xlsx')
data_Absen_2 = pd.read_excel('Absenteesim feb22.xlsx')
data_Absen_3 = pd.read_excel('Absenteesim mar22.xlsx')
data_Absen_4 = pd.read_excel('Absenteesim apr22.xlsx')
data_Absen_5 = pd.read_excel('Absenteesim may22.xlsx')
data_Absen_6 = pd.read_excel('Absenteesim jun22.xlsx')

or you can consider automating this

data_Absen_1 = data[0]
data_Absen_2 = data[1]
data_Absen_3 = data[2]
data_Absen_4 = data[3]
2
  • because this line data = data[i] overwrites data variable on every iteration. you can do something like this result = [] result.append(data[i]) Commented Nov 18, 2022 at 14:28
  • yeah, so how can we do this? Commented Nov 18, 2022 at 14:29

1 Answer 1

1

You could use exec

# let's create a list for testing purposes
data = list(range(100))

# to assign the 10 first values
for i in range(10):
    exec(f'data_Absen_{i+1} = data[{i}]')

Then you can directly access your variables

print(data_Absen_6)  # returns 5
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.