2
votes

My actual example is more involved so I boiled the concept down to a simple example:

l = [1,2,3,4,5,6,7,8]

for number in l:
    calc = number*10
    print calc

For each iteration of my loop, I end up with a variable (calc) I'd like to use to populate a new list. My actual process involves much more than multiplying the value by 10, so I'd like to be able to set each value in the new list by this method. The new code might look like this:

l = [1,2,3,4,5,6,7,8]

for number in l:
    calc = number*10
    # set calc as x'th entry in a new list called l2 (x = iteration cycle)

print l2

Then it would print the new list: [10,20,30,40,...]

7
Why can't you just do l2.append(calc)? - Ryan Saxe

7 Answers

7
votes

Here's how to do it without jumping straight into list comprehensions. It's not a great idea to use l as a variable name because it is identical to 1 in some fonts, so I changed it (althought l1 isn't really much better :) )

l1 = [1,2,3,4,5,6,7,8]
l2 = []
for number in l1:
    calc = number*10
    print calc
    l2.append(calc)

list comprehensions do provide a more compact way to write this pattern

l2 = [ number*10 for number in l1 ]
10
votes

There are several options...

List comprehensions

Use list comprehension, if short enough:

new_list = [number * 10 for number in old_list]

map()

You could also use map(), if the function exists before (or you will eg. use lambda):

def my_func(value):
    return value * 10

new_list = map(my_func, old_list)

Be aware, that in Python 3.x map() does not return a list (so you would need to do something like this: new_list = list(map(my_func, old_list))).

Filling other list using simple for ... in loop

Alternatively you could use simple loop - it is still valid and Pythonic:

new_list = []

for item in old_list:
    new_list.append(item * 10)

Generators

Sometimes, if you have a lot of processing (as you said you have), you want to perform it lazily, when requested, or just the result may be too big, you may wish to use generators. Generators remember the way to generate next element and forget whatever happened before (I am simplifying), so you can iterate through them once (but you can also explicitly create eg. list that stores all the results).

In your case, if this is only for printing, you could use this:

def process_list(old_list):
    for item in old_list:
        new_item = ...  # lots of processing - item into new_item
        yield new_item

And then print it:

for new_item in process_list(old_list):
    print(new_item)

More on generators you can find in Python's wiki: http://wiki.python.org/moin/Generators

Accessing "iteration number"

But if your question is more about how to retrieve the number of iteration, take a look at enumerate():

for index, item in enumerate(old_list):
    print('Item at index %r is %r' % (index, item))
3
votes

Use a list comprehension :

>>> l = [1,2,3,4,5,6,7,8]
>>> l2 = [ item*10 for item in l]
>>> l2
[10, 20, 30, 40, 50, 60, 70, 80]

Which is roughly equivalent to, but a list comprehension is faster than normal for-loop:

>>> l2 = []
>>> for number in l:
...     calc = number * 10  #do some more calculations
...     l2.append(calc)     #appends the final calculated value at the end of l2
...     
>>> l2
[10, 20, 30, 40, 50, 60, 70, 80]

You can also create a function for all the calculations you're doing, and then call the function inside the list comprehension :

def solve(x):
   #do some calculations here
   return calculated_value

l2 = [ solve(item) for item in l]
0
votes

So I believe you would like to apply a function to every element of the list.

Have you tried a list comprehension?

[num*10 for num in l]

Should give you what you need for this simple example.

Naturally, if you have some more complex set of operations you can use a function you defined earlier, to wit:

def explode(n):
    return (n + (n * n) - (3 * n))

[explode(num) for num in l]
0
votes

A simple answer to your problem would be to append calc to a list as shown below:

l = [1,2,3,4,5,6,7,8]

your_list = []
for number in l:
    calc = number*10
    your_list.append(calc)

To access variables in the list, use slicing syntax.

ie, the 2nd element in a list would be your_list[1], the 5th your_list[4].

I suspect you'll need to empty the list at some point. To do so with slicing, use calc[:] = []

0
votes

Everyone else has given you the right answer: use a list comprehension.

I will give you an alternate right answer: Use map with a lambda or a function.

You can use a lambda when the 'function' is very simple:

print map(lambda x: x*10,[1,2,3,4,5,6,7,8])
# [10, 20, 30, 40, 50, 60, 70, 80]

The function used by map can be of arbitrary complexity, and then it is easier use a function:

def more_complex(x):
    # can be as complex as a function can be
    # for now -- *10
    return x*10

print map(more_complex,[1,2,3,4,5,6,7,8])

But that would work with a comprehension as well:

l2=[more_complex(x) for x in [1,2,3,4,5,6,7,8]]

Just so that you are familiar with the form of map vs list comprehension.

0
votes

loop that generates the list

KOT = []
l = [1,2,3,4,5,6,7,8]


for number in l:
    calc = number*10
    KOT.append(calc)

You get the KOT list

KOT = [10, 20, 30, 40, 50, 60, 70, 80]