CPMAN
CPMAN

Reputation: 69

How to create incremental variables from a list which may vary in number of items. Python 3

I am a newbie. I have created a list from a .csv file:

 h = [2.3, 1.4, 4.5, 4.5, 1.4, 2.3]

The number of items in the list varies (from 2 to 36) depending on the .csv file. I want to create incremental variables from the list like this (so I can use them later in the code):

 L1 = 2.3
 L2 = 1.4
 L3 = 4.5
 L4 = 4.5
 L5 = 1.4
 L6 = 2.3

My problem is that the number of items in the list from the .csv file varies and I have tried using the increment and enumerate methods, but I cannot make it work at all.

Upvotes: 1

Views: 170

Answers (3)

Denys Halenok
Denys Halenok

Reputation: 93

If I understand you correctly, it would help to create a dict from the list.
You can use this dict comprehension statement.

h = [2.3, 1.4, 4.5, 4.5, 1.4, 2.3]

result = {f"L{index+1}": value for index, value in enumerate(h)}

> {'L1': 2.3, 'L2': 1.4, 'L3': 4.5, 'L4': 4.5, 'L5': 1.4, 'L6': 2.3}

And you can get the number which you need by specifying the key. For example:

print(result["L1"])

> 2.3

Upvotes: 2

Born Tbe Wasted
Born Tbe Wasted

Reputation: 610

I would suggest you stick with the list for storing data , and access it via h[i]

However , you can still have your wish using exec:

for i,x in enumerate(h):
    exec(f'L{i}=x')

Please note that the first L will be L0 , change the above code if you want to start with 1.

Upvotes: -1

glhr
glhr

Reputation: 4547

Instead of defining one variable for each element in the list, you can simply get the value of each element via its index:

h[0] # first element of the list (2.3)
h[1] # second element of the list (1.4)
h[2] # third element of the list (4.5)
# etc

which you can use like print(h[0]).

len(h) gives you the number of elements in h. The last element in the list has index len(h)-1 (5 in your example).

Upvotes: 0

Related Questions