Nacu
Nacu

Reputation: 3

writing iterable variable from a loop into a python list

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.

Upvotes: 0

Views: 102

Answers (3)

thebjorn
thebjorn

Reputation: 27311

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)

Upvotes: 1

Raymond Hettinger
Raymond Hettinger

Reputation: 226231

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))

Upvotes: 2

ndpu
ndpu

Reputation: 22561

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

Upvotes: 1

Related Questions