T
T
TreShk02018-03-05 12:03:58
Python
TreShk0, 2018-03-05 12:03:58

How to create a variable by the number of elements in the list and by their names?

How to create a variable from a list, for example, I have an arbitrary list, the list has any number of elements (here 3) and how to create the same number of variables depending on the number of elements? l = ['S', 'p', 'j']

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Kuts, 2018-03-05
@TreShk0

In general, you have strange requirements, but if you really need it, you can do it like this, for example:

>>> l = ['S', 'p', 'j']
>>> for im in l:
...    exec('{}=1'.format(im))
... 
>>> S
1
>>> j
1
>>> S+p+j
3
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>, 
  'j': 1, 
  'l': ['S', 'p', 'j'], 
  '__package__': None, 
  'p': 1, 
  'S': 1, 
  'im': 'j', 
  '__name__': '__main__', 
  '__doc__': None
}

or alternatively
>>> l = ['S', 'p', 'j']
>>> for im in l:
...    locals()[im] = 1
... 
>>> S+p+j
3

If I understand the question correctly.

B
blizzard, 2018-03-05
@s41blizzard

list_length = len(l) - the number of elements in the list.
It's not entirely clear what "and how to create as many variables depending on the number of elements" means?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question