0

Several questions related to the same issue have been posted, but do not find a solution to my problem. I would like to get the output of my loop (list of 2000 floats) into a python list. I am getting the "variable non iterable error" because I am not managing to call each of the elements of the output in the right way to be written into a list.

Other attempts, like converting to a list inside the loop, give me a list per element, when I need only one list with all the elements inside.

This is my code:

for i in range(x):
    timedelta= (function(i)) #datetime.timedelta elements 
    pos_time = (i, function(i)) #tuple of an integer and a float
    time = pos_time[1]
    print time

If I finish here I get the list of values I need:

3.5
2.04
6.6
4.02
...

If I continue inside the loop:

times = []
for time in range(x):
    times.append(time)

then I get a list from consecutive values, not really the output from the loop. What I need is a list like:

times = [3.5,2.04,6.6,4.02]

I would appreciate your help very much.

3 Answers 3

2

On your second attempt ("If I continue inside the loop"), you were very close, just add the function call:

times = []
for time in range(x):
    times.append(function(time))

Also, you might want to look at the map() function to build the list of function results directly:

 map(function, range(x))
Sign up to request clarification or add additional context in comments.

Comments

1
times = [function(i) for i in range(x)]

1 Comment

Thank you for your quick answer but I am afraid that does not give me what I want. I get arrays of 2000 equal elements that it is the first value of the loop.
1

Instead of printing, append to the times list:

times = []
for i in range(x):
    time= (function(i)) 
    pos_time = (i, function(i))
    time = pos_time[1]
    # print time 
    times.append(time)

I'm not sure I'm understanding what you're trying to do inside the for-loop though:

time= (function(i))

is the same as

time = function(i)

i.e. calling function with the loop variable as a paramter.

pos_time = (i, function(i))

creates a tuple of i the loop variable and a second call to function(i).

time = pos_time[1]

then gets the second/last value of the tuple you created.

If function(i) returns the same value every time you call it with i, you could simply do

times = []
for i in range(x):
    time = function(i)
    times.append(time)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.