2

How would i go about making a function to create a certain number of uniquely named variables at runtime, based on initial user input? For instance, user enters dimensions 400 x 400, (x and y), so i would want the function to create 1600 (400 * 400) variables, each to represent every different point on a grid 400 by 400.

2 Answers 2

2

What you really want is an array, a list or a tuple of 400*400 points.

So create a class that stores the information you want at each point, and then create a list of size 400*400 of those class objects.

You can do it this way:

width = 400
height = 400
m = [[0]*width for i in range(height)]

And then access points in your field like so:

m[123][105] = 7

To set point (123,105) to 7.

If you want to store more than just a number at each point, create a class like I suggested:

class MyClass:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

And then create your list of "MyClass" objects like so:

m = [[MyClass(0,0,0) for i in range(400)] for j in range(400)]
Sign up to request clarification or add additional context in comments.

5 Comments

Sweet. Thank you, i should be able to implement that into my code.
An array is not a tuple nor is it a list. A tuple is immutable and has fixed length. A list is mutable but has a dynamic length. An array is mutable and (usually) has a static length. (The latter is due to the underlying structure of one big solid block making insertions and deletions a rather costly affair).
400x400 would take a trifling (by today's standards) meg or two. For storing something larger I'd use a list of array-s from same-named module, and for things that are seriously larger, numpy. It seems that simple integers are stored anyway, not arbitrary objects. E.g. initializer = [0]*width; matrix = [array('i', initializer) for x in range(height)]
[MyClass(0,0,0)]*400 creates 400 references to the same object. You'll need [[MyClass(0,0,0) for i in range(400)] for j in range(400)].
Thanks Mark, you're right. I guess my Python is rustier than I thought :)
1

Are you sure you need to create a different variable for each point on the grid? If there are lots of points with default value of say 0, don't create an array with a bunch of 0s. Instead, create an empty dictionary D = {}. Store data as D[(x,y)] = anything. Access your data by D.get((x,y), 0). Where D.get(key, default value) This saves memory.

Btw, 400*400 is not 1600. Rather 160,000

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.