Christian
Christian

Reputation: 942

store a list into a variable from a for loop Python

So, the question by it's self sounds complex. I'm making a program that can read css files. Here's the full code if you want to see it ( http://pastebin.com/F09MScfp ). So I have a variable. (let's call it element) element is inside a for loop to get the styles and names. For example:

for elementName in contents.split('{'):
    element = elementName.split('}')

    print(element + '\n\n')
print(element)

results:

#For loop results
['#IDname', 'border:1px black solid;']
['.ClassName', 'border:3px blue solid']

#outside of loop (if global)
['IDname', 'border:1px black solid;']

So I need to be able to have an automated way of storing each list into a variable, like to call Element1 and get #IDname. Example: print(Element2) And get this as a result

['.ClassName', 'border:1px black solid']

So I was thinking of doing a loop inside that loop like so.

i=0
for i in element:
    i = 1+i
    exec('globals()Element+ %i = element' %i)
    #sorry, I'm still really new to python :(

Upvotes: 2

Views: 8033

Answers (2)

Nick Brady
Nick Brady

Reputation: 6572

This type of issue arises pretty often and a common solution is to just add the values to a list, or you could create a dictionary and reference the elements by keys. If you want to reference the elements by order added as in your example, you could do this.

elements = {} # Create empty dictionary
accumulator = 1
for element in itterable:
    elements[accumulator] = element # Assign value to a key where accumulator is the key
    accumulator += 1

When you do this, you can call element 2 with "elements[2]".

A list comprehension as Joran commented is the more "Pythonic" way to approach this. You could give each value in the list a value to reference similarly by enumerating the list comprehension adding the output as tuples to a list.

For example...

abc = 'abcdefghijklmnopqrstuvwxyz'
lst = [letter for letter in abc]
new_list = list(enumerate(lst,start=1))
print(new_list)

will output this:

[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'), (6, 'f'), (7, 'g'),     (8, 'h'), (9, 'i'), (10, 'j'), (11, 'k'), (12, 'l'), (13, 'm'), (14, 'n'), (15, 'o'), (16, 'p'), (17, 'q'), (18, 'r'), (19, 's'), (20, 't'), (21, 'u'), (22, 'v'), (23, 'w'), (24, 'x'), (25, 'y'), (26, 'z')]

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 113940

Store the elements in a list so you can access them later.

elements = [elementName.split("}") 
               for elementName in contents.split("{")]

print elements[0] # the first element
print elements[1] # the second element

Upvotes: 5

Related Questions