[Tutor] list generation
Peter Otten
__peter__ at web.de
Tue May 11 10:15:06 EDT 2021
On 11/05/2021 10:47, Alan Gauld wrote:
>
> On 11/05/2021 01:12, Ed Connell wrote:
>> Thanks for your help. (All)
>>
>> I was working with 'map' and the function that it was mapping needed
>> 2 arguments. The first was a list of values. The second was always
>> the same - like 2. Thus I needed a list of 2s or whatever at least as
>> long as the first list. (Like [ 2, 2, ...2 ]) Of course I could use
>> a simple loop. Then I hit on [ 2 for _ in range( length ) . But I
>> like yours best - [ 2 ] * length. Thanks again.
>
> The usual way I'd solve that is to use a lambda expression:
>
> result = map(lambda x: foo(x,2), collection)
For completeness I'd like to mention what has become the most common way
to spell this in Python:
result = [foo(x, 2) for x in collection]
> Which will call the lamba with x from collection.
>
> Then the lambda calls foo() with x as the first and 2 as the second
> argument.
More information about the Tutor
mailing list