Q:Pythonic way to create list of lists
Terry Reedy
tjreedy at udel.edu
Sat Apr 11 17:37:46 EDT 2009
grkuntzmd at gmail.com wrote:
> I am just learning Python.
>
> I am trying to create a list of empty lists: [[], [], [], ...] (10
> items total).
>
> What is the most Pythonic way to do this?
>
> If I use a list comprehension (as in myList = [[] for item in xrange
> (0, 10)]), Netbeans warns me that 'item' is never used.
Never heard of netbeans, but a decent code checker should have a
mechanism to annotate (comment) code to say "I know what I am doing
here, shut up".
> If I use a for-loop (as in for item in myList = []; for item in xrange
> (0, 10): myList.append([])), Netbeans still warns me of the same
> thing.
Adding something stupic like 'item = item' in the loop might 'work' ;-)
> If I use '*' (as myList = [[]] * 10), all of the empty lists refer to
> the same object; changing one changes them all.
Right. Typical newbie mistake. Good for you for discovering that yourself.
> Do I have to live with the warning, or is there a "better" way?
Different checker? PyChecker? PhLint?
tjr
More information about the Python-list
mailing list