# Optimizing and clarifying nested list appending

I have such part in my script, how can I optimize such parts? I don't want to use many local variables.

size_variants = []
for size in sizes_list:
size_variants.append({'size': size})


Also here:

variants_tmp = list()
all_color_list = list(get_all_colors())
[variants_tmp.extend(var) for var in all_color_list]

-

Using a list comprehension means you can eliminate all local variables:

size_variants = [{'size': size} for size in sizes_list]


Generally, anything of the form:

<new list initialization>
for <variable> in <list>:
<new list>.append(<variable>)


can be written much more cleanly in list comprehension form.

Edit: If you want to extend an already existing list, and you have something like a nested list, then you'll probably want to use itertools.chain:

import itertools
x = [1, 2, 3]
y = [[4, 5], [6, 7, 8], [9, 10]
x = x + [i for i in itertools.chain.from_iterable(y)]


which will have x == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].

-
but what if I need not to append, but extend? –  user2734570 Jul 25 at 9:31
@user: You can still use a list comprehension, since extend takes a generator too. –  Hurkyl Jul 25 at 10:19
@Hurkyl im trying but it is crashing here: variants_tmp = list() all_color_list = list(get_all_colors()) [variants_tmp.extend(var) for var in all_color_list] –  user2734570 Jul 25 at 10:23
@user: nono, you pass the generator expression into extend, not call extend` in the generator expression. –  Hurkyl Jul 25 at 10:24
@Hurkyl still dont understand, sorry :( –  user2734570 Jul 25 at 10:48