-2

I am creating this topic because I would like to iterate over Objects that have nearly the same name without having to copy/paste the code a lot of times.

For instance let's say we have a "class Car " and we have : 100 instances of Car like that :

Car_1 = Car()
Car_2 = Car()
...
Car_100 = Car()

How can we iterate over these objects ? PS : In case eval() is a solution, I don't want to use that since string processing takes a long time

Walid
  • 29
  • 3

1 Answers1

0

When you want a lot of Car()s, you put them in a list. Then it is easy to iterate over them:

cars = [Car() for _ in range(100)]
for car in cars:
    car.honk()
quamrana
  • 37,849
  • 12
  • 53
  • 71
  • Thank you so much for your answer @quamrana, but for some reason I don't have them as a list because they come from another environment, I mean I just have access to each one. In other words, I'm not the one creating them, they're already created and accessible – Walid Jul 11 '22 at 08:06
  • 1
    That makes no sense. You had better get them in a list as soon as possible. The answers to this [question](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) should help you. – quamrana Jul 11 '22 at 08:07