Python Forum
Best way to accommodate unknown number of variables?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Best way to accommodate unknown number of variables?
#5
Here a kind of hidden👻 secrets.
>>> dte1 = 1
>>> dte2 = 2
>>> dte3 = 3
When make 3 variables like this Python store them in a internal dictionary called globals()
Can test this with:
>>> globals()['dte3']
3
>>> globals().get('dte1')
1
So as mention use a data structure like eg dictionary and do not make 50 variables.
>>> d = {f'dte{i}':i for i in range(0,10)}
>>> d
{'dte0': 0,
 'dte1': 1,
 'dte2': 2,
 'dte3': 3,
 'dte4': 4,
 'dte5': 5,
 'dte6': 6,
 'dte7': 7,
 'dte8': 8,
 'dte9': 9}

# Same result but now have made a own visible dictionary
>>> d['dte3']
3
>>> d.get('dte1')
1
Mark17 likes this post
Reply


Messages In This Thread
RE: Best way to accommodate unknown number of variables? - by snippsat - May-20-2022, 06:20 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Create X Number of Variables and Assign Data RockBlok 8 1,047 Nov-14-2023, 08:46 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020