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.
7,122
questions
1681
votes
13
answers
2.0m
views
if/else in a list comprehension
How do I convert the following for-loop containing an if/else into a list comprehension?
results = []
for x in xs:
results.append(f(x) if x is not None else '')
It should yield '' if x is None, ...
1573
votes
17
answers
1.2m
views
Create a dictionary with comprehension
Can I use list comprehension syntax to create a dictionary?
For example, by iterating over pairs of keys and values:
d = {... for k, v in zip(keys, values)}
1052
votes
31
answers
730k
views
How do I remove duplicates from a list, while preserving order?
How do I remove duplicates from a list, while preserving order? Using a set to remove duplicates destroys the original order.
Is there a built-in or a Pythonic idiom?
971
votes
14
answers
336k
views
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?
784
votes
10
answers
997k
views
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 ...
690
votes
8
answers
1.2m
views
if else in a list comprehension [duplicate]
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 ...
532
votes
13
answers
227k
views
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 ...
528
votes
13
answers
209k
views
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)]
523
votes
9
answers
538k
views
Python Dictionary Comprehension [duplicate]
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 ...
431
votes
23
answers
220k
views
Flattening a shallow list in Python [duplicate]
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 ...
400
votes
11
answers
371k
views
Double Iteration in List Comprehension [duplicate]
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 ...
351
votes
13
answers
248k
views
How can I use list comprehensions to process 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', ...
331
votes
11
answers
357k
views
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 ...
306
votes
2
answers
253k
views
How to unzip a list of tuples into individual lists? [duplicate]
I have a list of tuples l = [(1,2), (3,4), (8,9)]. How can I, succinctly and Pythonically, unzip this list into two independent lists, to get [ [1, 3, 8], [2, 4, 9] ]?
In other words, how do I get the ...
290
votes
6
answers
213k
views
Is it possible to use 'else' in a list comprehension? [duplicate]
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
...
275
votes
3
answers
191k
views
How can I create a list of elements from an iterator (convert the iterator to a list)?
Given an iterator user_iterator, how can I iterate over the iterator a list of the yielded objects?
I have this code, which seems to work:
user_list = [user for user in user_iterator]
But is there ...
254
votes
6
answers
463k
views
How can I use a conditional expression (expression with if and else) in a list comprehension? [duplicate]
I have a list comprehension that produces list of odd numbers of a given range:
[x for x in range(1, 10) if x % 2]
That makes a filter that removes the even numbers. Instead, I'd like to use ...
247
votes
9
answers
32k
views
Accessing class variables from a list comprehension in the class definition
How do you access other class variables from a list comprehension within the class definition? The following works in Python 2 but fails in Python 3:
class Foo:
x = 5
y = [x for i in range(1)]...
234
votes
8
answers
178k
views
Are list-comprehensions and functional functions faster than "for loops"?
In terms of performance in Python, is a list-comprehension, or functions like map(), filter() and reduce() faster than a for loop? Why, technically, they run in a C speed, while the for loop runs in ...
233
votes
19
answers
740k
views
Creating a dictionary from a csv file?
I am trying to create a dictionary from a csv file. The first column of the csv file contains unique keys and the second column contains values. Each row of the csv file represents a unique key, value ...
226
votes
6
answers
188k
views
`elif` in list comprehension conditionals
Consider this example:
l = [1, 2, 3, 4, 5]
for values in l:
if values == 1:
print('yes')
elif values == 2:
print('no')
else:
print('idle')
Rather than printing ...
187
votes
7
answers
109k
views
How to handle exceptions in a list comprehensions?
I have some a list comprehension in Python in which each iteration can throw an exception.
For instance, if I have:
eggs = (1,3,0,3,2)
[1/egg for egg in eggs]
I'll get a ZeroDivisionError ...
186
votes
10
answers
342k
views
How to remove multiple items from a list in just one statement?
In python, I know how to remove items from a list:
item_list = ['item', 5, 'foo', 3.14, True]
item_list.remove('item')
item_list.remove(5)
The above code removes the values 5 and 'item' from ...
177
votes
4
answers
420k
views
Apply function to each element of a list [duplicate]
Suppose I have a list like:
mylis = ['this is test', 'another test']
How do I apply a function to each element in the list? For example, how do I apply str.upper to get:
['THIS IS TEST', 'ANOTHER ...
176
votes
6
answers
236k
views
How to frame two for loops in list comprehension python
I have two lists as below
tags = [u'man', u'you', u'are', u'awesome']
entries = [[u'man', u'thats'],[ u'right',u'awesome']]
I want to extract entries from entries when they are in tags:
result = []
...
164
votes
3
answers
39k
views
Are for-loops in pandas really bad? When should I care?
Are for loops really "bad"? If not, in what situation(s) would they be better than using a more conventional "vectorized" approach?1
I am familiar with the concept of "vectorization", and how pandas ...
150
votes
4
answers
121k
views
In Python list comprehension is it possible to access the item index?
Consider the following Python code with which I add in a new list2 all the items with indices from 1 to 3 of list1:
for ind, obj in enumerate(list1):
if 4 > ind > 0:
list2.append(obj)...
147
votes
7
answers
296k
views
Python using enumerate inside list comprehension
Lets suppose I have a list like this:
mylist = ["a","b","c","d"]
To get the values printed along with their index I can use Python's enumerate function like this
>>> for i,j in enumerate(...
144
votes
5
answers
237k
views
List comprehension with if statement
I want to compare 2 iterables and print the items which appear in both iterables.
>>> a = ('q', 'r')
>>> b = ('q')
# Iterate over a. If y not in b, print y.
# I want to see ['r'] ...
144
votes
13
answers
630k
views
Pythonic way to print list items
I would like to know if there is a better way to print all objects in a Python list than this :
myList = [Person("Foo"), Person("Bar")]
print("\n".join(map(str, myList)))
Foo
Bar
I read this way is ...
142
votes
5
answers
374k
views
Single Line Nested For Loops [duplicate]
Wrote this function in python that transposes a matrix:
def transpose(m):
height = len(m)
width = len(m[0])
return [ [ m[i][j] for i in range(0, height) ] for j in range(0, width) ]
In ...
138
votes
8
answers
61k
views
List comprehension: Returning two (or more) items for each item [duplicate]
Is it possible to return 2 (or more) items for each item in a list comprehension?
What I want (example):
[f(x), g(x) for x in range(n)]
should return [f(0), g(0), f(1), g(1), ..., f(n-1), g(n-1)]
...
134
votes
7
answers
17k
views
Is it Pythonic to use list comprehensions for just side effects?
Think about a function that I'm calling for its side effects, not return values (like printing to screen, updating GUI, printing to a file, etc.).
def fun_with_side_effects(x):
...side effects...
...
132
votes
6
answers
19k
views
List comprehension rebinds names even after scope of comprehension. Is this right?
Comprehensions show unusual interactions with scoping. Is this the expected behavior?
x = "original value"
squares = [x**2 for x in range(5)]
print(x) # Prints 4 in Python 2!
At the risk ...
126
votes
4
answers
48k
views
Line continuation for list comprehensions or generator expressions in python
How are you supposed to break up a very long list comprehension?
[something_that_is_pretty_long for something_that_is_pretty_long in somethings_that_are_pretty_long]
I have also seen somewhere that ...
117
votes
18
answers
97k
views
How can I get a flat result from a list comprehension instead of a nested list?
I have a list A, and a function f which takes an item of A and returns a list. I can use a list comprehension to convert everything in A like [f(a) for a in A], but this returns a list of lists. ...
115
votes
4
answers
107k
views
Nested For Loops Using List Comprehension [duplicate]
If I had two strings, 'abc' and 'def', I could get all combinations of them using two for loops:
for j in s1:
for k in s2:
print(j, k)
However, I would like to be able to do this using list ...
112
votes
8
answers
95k
views
How can I do assignments in a list comprehension?
I want to use the assignment operator in a list comprehension. How can I do that?
The following code is invalid syntax. I mean to set lst[0] to an empty string '' if it matches pattern:
[ lst[0] = ''...
111
votes
7
answers
31k
views
List comprehension without [ ] in Python
Joining a list:
>>> ''.join([ str(_) for _ in xrange(10) ])
'0123456789'
join must take an iterable.
Apparently, join's argument is [ str(_) for _ in xrange(10) ], and it's a list ...
109
votes
5
answers
158k
views
Python for-in loop preceded by a variable [duplicate]
I saw some code like:
foo = [x for x in bar if x.occupants > 1]
What does this mean, and how does it work?
108
votes
17
answers
58k
views
List comprehension in Ruby
To do the equivalent of Python list comprehensions, I'm doing the following:
some_array.select{|x| x % 2 == 0 }.collect{|x| x * 3}
Is there a better way to do this...perhaps with one method call?
103
votes
5
answers
128k
views
Flattening a list of NumPy arrays?
It appears that I have data in the format of a list of NumPy arrays (type() = np.ndarray):
[array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]),
array([[ 0.00353654]]), array([[ 0....
101
votes
10
answers
40k
views
How can I get around declaring an unused variable in a list comprehension?
If I have a list comprehension (for example) like this:
['' for x in myList]
Effectively making a new list that has an empty string for every element in a list, I never use the x. Is there a cleaner ...
98
votes
3
answers
51k
views
What do backticks mean to the Python interpreter? Example: `num`
I'm playing around with list comprehensions and I came across this little snippet on another site:
return ''.join([`num` for num in xrange(loop_count)])
I spent a few minutes trying to replicate the ...
94
votes
7
answers
113k
views
Add an element in each dictionary of a list (list comprehension)
I have a list of dictionaries, and want to add a key for each element of this list.
I tried:
result = [ item.update({"elem":"value"}) for item in mylist ]
but the update method returns None, so my ...
92
votes
2
answers
53k
views
Why is a list comprehension so much faster than appending to a list?
I was wondering why list comprehension is so much faster than appending to a list. I thought the difference is just expressive, but it's not.
>>> import timeit
>>> timeit.timeit(...
90
votes
4
answers
72k
views
python list comprehension double for
vec = [[1,2,3], [4,5,6], [7,8,9]]
print [num for elem in vec for num in elem] <----- this
>>> [1, 2, 3, 4, 5, 6, 7, 8, 9]
This is tricking me out.
I understand elem is the lists ...
88
votes
10
answers
77k
views
Using break in a list comprehension
How can I break a list comprehension based on a condition, for instance when the number 412 is found?
Code:
numbers = [951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544,
...
88
votes
4
answers
21k
views
Alternative to list comprehension if there will be only one result
I'm starting to get used to list comprehension in Python but I'm afraid I'm using it somewhat improperly. I've run into a scenario a few times where I'm using list comprehension but immediately ...
88
votes
5
answers
25k
views
Does PHP have an equivalent to Python's list comprehension syntax?
Python has syntactically sweet list comprehensions:
S = [x**2 for x in range(10)]
print S;
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In PHP I would need to do some looping:
$output = array();
$Nums = ...