Michael Falk Vedel
Michael Falk Vedel

Reputation: 29

Nested variable creation

I'm currently writing some code in python(3.6), and as I have quite a few variables with the same name (The only identifier is the ID of that variable.), I was wondering if it would be possible to do something like this:

for i in range(0.1):
        mapped_data{i} = 4

So like with strings and formatting hereof.

Or is the best way to do this, to create a (sometimes nested) list, with the size of how many variables I need of a particular variables?

Upvotes: 1

Views: 78

Answers (1)

Olivier Melançon
Olivier Melançon

Reputation: 22314

Relying on numbered variable names is generally a bad practice. It pollutes your scope, making your code less maintainable and readable.

A sequence of values should typically be stored in a list. Note that since Python uses lists instead of arrays you do not have to worry about the size of that list.

mapped_data = []

for i in range(0, 10):
    mapped_data.append(4)

mapped_data[2] # 4

A group of labeled values which order does not matter should be stored in a dict.

mapped_data = {}

for name in ('foo', 'bar', 'baz'):
    mapped_data[name] = 4

mapped_data['foo'] # 4

Upvotes: 1

Related Questions