Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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]
share|improve this question
up vote 6 down vote accepted

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].

share|improve this answer
but what if I need not to append, but extend? – user2734570 Jul 25 '14 at 9:31
@user: You can still use a list comprehension, since extend takes a generator too. – Hurkyl Jul 25 '14 at 10:19
@Hurkyl i`m 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 '14 at 10:23
@user: nono, you pass the generator expression into extend, not call extend in the generator expression. – Hurkyl Jul 25 '14 at 10:24
@Hurkyl still dont understand, sorry :( – user2734570 Jul 25 '14 at 10:48

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.