Imam Abdul Mahmudi
Imam Abdul Mahmudi

Reputation: 303

Save Numbered Variable

I want to save my list to numbered variable.

myList =[1,2,3,4,5]

and I want save be like this :

numb1 = myList[1]
numb2 = myList[2]
numb3 = myList[3]
numb4 = myList[4]
numb5 = myList[5]

I don't want do it manually, because myList contains many elements. Can you give me suggestion?

Upvotes: 2

Views: 78

Answers (2)

TigerhawkT3
TigerhawkT3

Reputation: 49320

This is an XY Problem in which problem X (i.e., referring to elements in a list) is much easier than problem Y (i.e., creating a series of numbered variables corresponding to elements in a list). On top of that, doing this would defeat the entire purpose of using a list. It doesn't take too long to hard-code it for the five elements you showed, but the list with "many elements" you mention should not be given this treatment.

A list holds several objects, generally of a homogeneous type and purpose, like inches of rainfall on each day of the year. This data structure makes it easy to store and process all of these objects together. You can also refer to them individually, by indexing.

Where you are hoping to refer to the first element of myList as numb1, use instead myList[0]. That is the reference that you already have for that object. You do not need to pollute the namespace with a pile of numbered references. The list type is intended precisely for this situation. Please use a list.

Upvotes: 1

Remi Guan
Remi Guan

Reputation: 22282

You could simply do this via enumerate():

>>> myList =[1,2,3,4,5,6,7,8,9,10]
>>> for index, value in enumerate(myList, start=1):
...     globals()['numb'+str(index)] = value
...     
... 
>>> numb1
1
>>> numb2
2
>>> numb3
3
>>> numb10
10
>>> 

But I'd recommend use another dict instead of globals():

>>> myList =[1,2,3,4,5,6,7,8,9,10]
>>> d = {}
>>> for index, value in enumerate(myList, start=1):
...     d['numb'+str(index)] = value
...     
... 
>>> d['numb1']
1
>>> d['numb2']
2
>>> d['numb10']
10
>>> 

Upvotes: 2

Related Questions