Questions tagged [list-comprehension]

A syntactic construct which provides a concise way to create lists in a style similar to the mathematical set-builder notation. Since several languages support list comprehensions, please use this tag in conjunction with the tag of a programming language.

A list comprehension can be used to construct lists in a very natural, easy way, like a mathematician is used to do. The resulting list definition often tends to be clearer and more concise than lists built using a different approach such as nested for or while loops.

List comprehensions tend to consist of an input list or lists, variable bindings, filtering predicates and an output expression, and more or less follow the mathematical set-builder notation in most programming languages which support them.

See also: http://en.wikipedia.org/wiki/List_comprehension

5834 questions
1392
votes
14 answers

Create a dictionary with list comprehension

I like the Python list comprehension syntax. Can it be used to create dictionaries too? For example, by iterating over pairs of keys and values: mydict = {(k,v) for (k,v) in blah blah blah} # doesn't work
flybywire
  • 232,954
  • 184
  • 384
  • 491
1189
votes
11 answers

if/else in a list comprehension

How can I do the following in Python? row = [unicode(x.strip()) for x in row if x is not None else ''] Essentially: replace all the Nones with empty strings, and then carry out a function.
AP257
  • 72,861
  • 84
  • 184
  • 258
819
votes
12 answers

List comprehension vs map

Is there a reason to prefer using map() over list comprehension or vice versa? Is either of them generally more efficient or considered generally more pythonic than the other?
TimothyAWiseman
  • 12,609
  • 11
  • 32
  • 47
605
votes
7 answers

Create list of single item repeated N times

I want to create a series of lists, all of varying lengths. Each list will contain the same element e, repeated n times (where n = length of the list). How do I create the lists, without using a list comprehension [e for number in xrange(n)] for…
chimeracoder
  • 17,532
  • 20
  • 57
  • 59
534
votes
8 answers

if else in a list comprehension

I have a list l: l = [22, 13, 45, 50, 98, 69, 43, 44, 1] For numbers above 45 inclusive, I would like to add 1; and for numbers less than it, 5. I tried [x+1 for x in l if x >= 45 else x+5] But it gives me a syntax error. How can I achieve an if –…
user225312
  • 108,033
  • 64
  • 161
  • 179
447
votes
10 answers

Generator expressions vs. list comprehensions

When should you use generator expressions and when should you use list comprehensions in Python? # Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)]
readonly
  • 306,152
  • 101
  • 198
  • 201
423
votes
9 answers

Python Dictionary Comprehension

Is it possible to create a dictionary comprehension in Python (for the keys)? Without list comprehensions, you can use something like this: l = [] for n in range(1, 11): l.append(n) We can shorten this to a list comprehension: l = [n for n in…
Rushy Panchal
  • 14,511
  • 14
  • 52
  • 87
401
votes
23 answers

Flattening a shallow list in Python

Is there a simple way to flatten a list of iterables with a list comprehension, or failing that, what would you all consider to be the best way to flatten a shallow list like this, balancing performance and readability? I tried to flatten such a…
prairiedogg
  • 6,163
  • 8
  • 40
  • 52
392
votes
11 answers

Why is there no tuple comprehension in Python?

As we all know, there's list comprehension, like [i for i in [1, 2, 3, 4]] and there is dictionary comprehension, like {i:j for i, j in {1: 'a', 2: 'b'}.items()} but (i for i in (1, 2, 3)) will end up in a generator, not a tuple comprehension.…
284
votes
11 answers

Double Iteration in List Comprehension

In Python you can have multiple iterators in a list comprehension, like [(x,y) for x in a for y in b] for some suitable sequences a and b. I'm aware of the nested loop semantics of Python's list comprehensions. My question is: Can one iterator in…
ThomasH
  • 19,270
  • 9
  • 53
  • 57
276
votes
6 answers

Python's most efficient way to choose longest string in list?

I have a list of variable length and am trying to find a way to test if the list item currently being evaluated is the longest string contained in the list. And I am using Python 2.6.1 For example: mylist = ['abc','abcdef','abcd'] for each in…
user104997
  • 2,795
  • 2
  • 15
  • 7
269
votes
12 answers

remove None value from a list without removing the 0 value

This was my source I started with. My List L = [0, 23, 234, 89, None, 0, 35, 9] When I run this : L = filter(None, L) I get this results [23, 234, 89, 35, 9] But this is not what I need, what I really need is : [0, 23, 234, 89, 0, 35,…
mongotop
  • 5,758
  • 13
  • 43
  • 70
266
votes
2 answers

How to unzip a list of tuples into individual lists?

Possible Duplicate: A Transpose/Unzip Function in Python I have a list of tuples, where I want to unzip this list into two independent lists. I'm looking for some standardized operation in Python. >>> l = [(1,2), (3,4), (8,9)] >>> f_xxx (l) […
VaidAbhishek
  • 5,275
  • 7
  • 35
  • 53
258
votes
12 answers

List comprehension on a nested list?

I have this nested list: l = [['40', '20', '10', '30'], ['20', '20', '20', '20', '20', '30', '20'], ['30', '20', '30', '50', '10', '30', '20', '20', '20'], ['100', '100'], ['100', '100', '100', '100', '100'], ['100', '100', '100', '100']] Now, what…
Boy Pasmo
  • 6,923
  • 9
  • 35
  • 55
235
votes
6 answers

Is it possible to use 'else' in a list comprehension?

Here is the code I was trying to turn into a list comprehension: table = '' for index in xrange(256): if index in ords_to_keep: table += chr(index) else: table += replace_with Is there a way to add the else statement to this…
Josh
  • 3,917
  • 5
  • 23
  • 27
1
2 3
99 100