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 Answers 7
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))
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 ]
-
I have a question. Why does Python assign the value 8 to number and store it as a variable when running this code? Nice solution.Seanosapien– Seanosapien2016年10月12日 17:52:05 +00:00Commented Oct 12, 2016 at 17:52
-
@Seanosapien, do you mean why
number
is in scope after the loop completes? Python loops don't create a new scope, so any variables created inside will remain in the function's scope (or the global scope if your loop isn't in a function)John La Rooy– John La Rooy2016年10月12日 23:14:49 +00:00Commented Oct 12, 2016 at 23:14 -
@JohnLaRooy, Thanks for that. I just found it odd that the variable is stored when .append is used but not otherwise.Seanosapien– Seanosapien2016年10月13日 08:57:14 +00:00Commented Oct 13, 2016 at 8:57
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]
-
Thanks for the tip. I have a lot of calculations going on in my actual example, so I want to be able to populate the list from a variable in the loop. Your example would solve the x10 question, but my problem involves a lot of lookups and calculations to get to the dependent variable determined. I can calculate the value I want within the loop just fine, so I want to use that variable to populate each item in a list for every iteration of the loop.bigCow– bigCow2013年06月03日 01:26:07 +00:00Commented Jun 3, 2013 at 1:26
-
@bigCow use the second method then, which uses
list.append
.Ashwini Chaudhary– Ashwini Chaudhary2013年06月03日 01:28:17 +00:00Commented Jun 3, 2013 at 1:28 -
@bigCow: It often depends on whether you have that "lots of lookups and calculations" encapsulated in a single function - depending on that, comprehensions, loops or mappings (see my answer) are more or less appropriate. It mostly comes down to how nice it looks or how flexible should be the code, but there is also slight speed difference (if you have preexisting function,
map()
may be the most efficient).Tadeck– Tadeck2013年06月03日 01:31:19 +00:00Commented Jun 3, 2013 at 1:31 -
@Tadeck I don't think people like
map
much : stackoverflow.com/a/16329617/846892Ashwini Chaudhary– Ashwini Chaudhary2013年06月03日 01:34:49 +00:00Commented Jun 3, 2013 at 1:34 -
@AshwiniChaudhary: Some people surely do not like
map()
, but it still has its uses. The proof that it is still necessary, is the fact thatmap()
has not been removed from built-ins in Python 3.x despite eg. movingreduce()
to one of the modules: docs.python.org/3.1/library/functions.html#mapTadeck– Tadeck2013年06月03日 01:41:23 +00:00Commented Jun 3, 2013 at 1:41
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.
-
It's worth noting that
map
is a generator in Python 3, so you'd need to wrap it in a call tolist
if you want to do any indexing, or anything else that requires an actual list.Blckknght– Blckknght2013年06月03日 02:26:00 +00:00Commented Jun 3, 2013 at 2:26
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]
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[:] = []
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]
l2.append(calc)
?