for loop without variable

Tim Chase python.list at tim.thechases.com
Fri Jan 11 17:41:52 EST 2008


>> I recently faced a similar issue doing something like this:
>>
>>     data_out = []
>>     for i in range(len(data_in)):
>>         data_out.append([])
> 
>     Another way to write this is
> data_out = [[]] * len(data_in)

...if you're willing to put up with this side-effect:

>>> data_in = range(10)
>>> data_out = [[]] * len(data_in)
>>> data_out
[[], [], [], [], [], [], [], [], [], []]
>>> data_out[0].append('hello')
>>> data_out
[['hello'], ['hello'], ['hello'], ['hello'], ['hello'],
['hello'], ['hello'], ['hello'], ['hello'], ['hello']]

For less flakey results:

>>> data_out = [[] for _ in data_in]
>>> data_out
[[], [], [], [], [], [], [], [], [], []]
>>> data_out[0].append('hello')
>>> data_out
[['hello'], [], [], [], [], [], [], [], [], []]


-tkc





More information about the Python-list mailing list