0

How can I assign values to variables by using two lists:

Numbers =[1,2,3,4,]
Element= ["ElementA","ElementB","ElementC","ElementD"]
for e, n in zip(Element, Numbers):
    e+ ' = ' +n   #this part is wrong 

What i want is a result like this in the end:

print ElementA
>1
print ElementB
>2
print ElementC
>3
print ElementD
>4

So what im trying to do is to fill up variables created from one list (Element) with values from another list (Numbers) in a kind of loop style. Does anyone know how to archive something like that? It should also be possible to assign many values contained in a list/array to variables.

4
  • use a dictionary d = dict(zip(Element, Numbers)) Commented Aug 27, 2015 at 23:12
  • O.k. if making something like that is unusual in python, so how do I load different data/values dynamically into python. Lets say I have a list of files and want to load all those files into python under their corresponding file names? Well Im more into R so Im not that into the python way of thinking yet. Commented Aug 28, 2015 at 9:21
  • do you mean open the files? Commented Aug 28, 2015 at 10:48
  • Something like that. In my very concrete case Im using laspy to open/connect a .las file in/to python. Well i can read out which information is available (and i want to save all that information to the corresponding variables). Then if i write Xcoordinate = mydataname.X i can save all X values in the variable Xcoordinate. And i want to do that for all the available information (X, Y, Z, classification etc.) not having to read the information out manually and type that code 8 times. Always just changing the variable name and the part behind the point mydataname.(X,Y,Z etc) Commented Aug 29, 2015 at 11:54

2 Answers 2

1

Do not do that.

You're already working with lists, so just create a list instead of hacking some hard-coded names. You could use a dictionary if you really wanted to use identifiers like A, B, etc., but you'd have a problem with more than 26 items, and you're just using it to make a sequence anyway. Integers are great for that, and of course we'll start at 0 because that's how it works.

>>> numbers = [1, 2, 3, 4]
>>> elements = [item for item in numbers]
>>> elements[0]
1

And at this point we can see that, for this example at least, you already had what you were looking for this whole time, in numbers.

>>> numbers = [1, 2, 3, 4]
>>> numbers[0]
1

Perfect.

Sign up to request clarification or add additional context in comments.

Comments

0

You may use exec but this is generally the wrong way to go.

for e, n in zip(Element, Numbers):
    exec(e + ' = ' + n)

You better should use a dictionnary:

my_dict = {}
for e, n in zip(Element, Numbers):
    my_dict[e] = n

Even simpler:

my_dict = dict(zip(Element, Numbers))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.