Many newbie questions regarding python

Ethan Furman ethan at
Sun Oct 10 04:30:16 CEST 2010

Steven D'Aprano wrote:
> And how often do you have an list that you are creating where you don't 
> know what items you have to initialise the list with?


> You are right to point out that the third case is a Python gotcha: [[]]*n 
> doesn't behave as expected by the naive or inexperienced Python 
> programmer. I should have mentioned it, and pointed out that in that case 
> you do want a list comp [[] for i in range(n)].
> But that doesn't mean that the list comp is the general purpose solution. 
> Consider the obvious use of the idiom:
> def func(arg, count):
>     # Initialise the list.
>     L = [arg for i in range(count)]
>     # Do something with it.
>     process(L, some_function)
> def process(L, f):
>     # Do something with each element.
>     for item in enumerate(L):
>         f(item)
> Looks good, right? But it isn't, because it will suffer the exact same 
> surprising behaviour if f modifies the items in place. Using a list comp 
> doesn't save you if you don't know what the object is.

I've only been using Python for a couple years on a part-time basis, so 
I am not aquainted with this obvious use -- could you give a more 
concrete example?  Also, I do not see what the list comp has to do with 
the problem in process() -- the list has already been created at that 
point, so how is it the list comp's fault?


More information about the Python-list mailing list