3

I have a class called Points and I need to create 100 points. I need to do something like:

class Point(object)
...

for i in range(1,100):
    pi = Point()

the points should be named p1, p2, ... p100

The lines above do not work, obviously.

The question is: I know that I could use exec inside a loop to create the 100 points but is there any better way to do it without using exec?

David Cain
  • 16,484
  • 14
  • 65
  • 75
zplot
  • 31
  • 1
  • See [_Why you don't want to dynamically create variables_](http://stupidpythonideas.blogspot.com/2013/05/why-you-dont-want-to-dynamically-create.html). – martineau Jan 28 '14 at 20:16

3 Answers3

8

You can create several objects using list comprehension:

# 100 points in list
points = [Point() for _ in range(100)]
ndpu
  • 22,225
  • 6
  • 54
  • 69
5

Creating/using dynamic variables is considered a bad practice in Python. It is very easy for you to lose track of them, cause name collisions, etc.

Instead, you can use a dict comprehension and str.format to create a dictionary of named instances:

points_dict = {"p{}".format(x):Point() for x in range(1, 101)}

Then, you can access those instances by name like so:

points_dict["p1"]
points_dict["p10"]
# etc.
  • Fixed. I actually changed my answer to use a dictionary comprehension so that the instances are named like the OP wanted. –  Jan 28 '14 at 19:18
0

Thank you very much for your answers. I learned a lot from them.

Anyway, I don't need a list of points or a dictionary of points.

Imagine I start writing:

p1 = Point() p2 = Point () . . . p100 = Point()

I will obtain 100 points and nothing more. That is what I need. I believe it is not a good practice to put in the program 100 lines of code as above! Additionally, the number of points to create will possibly be variable. That is why I thought there should be an elegant way to do it. Thank you.

zplot
  • 31
  • 1