All Questions
Tagged with list list-comprehension
2,260
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, ...
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?
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 ...
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 ...
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 = []
...
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
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 ...
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(...
83
votes
2
answers
5k
views
list() uses slightly more memory than list comprehension
So i was playing with list objects and found little strange thing that if list is created with list() it uses more memory, than list comprehension? I'm using Python 3.5.2
In [1]: import sys
In [2]: a ...
82
votes
14
answers
59k
views
python list comprehension to produce two values in one iteration
I want to generate a list in python as follows -
[1, 1, 2, 4, 3, 9, 4, 16, 5, 25 .....]
You would have figured out, it is nothing but n, n*n
I tried writing such a list comprehension in python as ...
72
votes
6
answers
15k
views
What does "list comprehension" and similar mean? How does it work and how can I use it?
I have the following code:
[x ** 2 for x in range(10)]
When I run it in the Python shell, it returns:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
I've searched and it seems this is called a list ...
62
votes
8
answers
72k
views
Counting positive integer elements in a list with Python list comprehensions
I have a list of integers and I need to count how many of them are > 0.
I'm currently doing it with a list comprehension that looks like this:
sum([1 for x in frequencies if x > 0])
It seems like ...
60
votes
8
answers
9k
views
Remove the first N items that match a condition in a Python list
If I have a function matchCondition(x), how can I remove the first n items in a Python list that match that condition?
One solution is to iterate over each item, mark it for deletion (e.g., by ...
58
votes
6
answers
126k
views
How can I call a method on each element of a List?
Suppose that I have a list of cars :
public class Car {
private String brand;
private String name;
private String color;
public Car() { // ... }
public getName() { return name; ...
58
votes
6
answers
43k
views
list.extend and list comprehension [duplicate]
When I need to add several identical items to the list I use list.extend:
a = ['a', 'b', 'c']
a.extend(['d']*3)
Result
['a', 'b', 'c', 'd', 'd', 'd']
But, how to do the similar with list ...
56
votes
6
answers
3k
views
List with duplicated values and suffix
I have a list, a:
a = ['a','b','c']
and need to duplicate some values with the suffix _ind added this way (order is important):
['a', 'a_ind', 'b', 'b_ind', 'c', 'c_ind']
I tried:
b = [[x, x + '...
54
votes
8
answers
89k
views
Picking out items from a python list which have specific indexes
I'm sure there's a nice way to do this in Python, but I'm pretty new to the language, so forgive me if this is an easy one!
I have a list, and I'd like to pick out certain values from that list. The ...
49
votes
1
answer
94k
views
How to return a subset of a list that matches a condition [duplicate]
Let's say I have a list of ints:
listOfNumbers = range(100)
And I want to return a list of the elements that meet a certain condition, say:
def meetsCondition(element):
return bool(element != 0 ...
47
votes
5
answers
92k
views
How do I get a list of indices of non zero elements in a list?
I have a list that will always contain only ones and zeroes.
I need to get a list of the non-zero indices of the list:
a = [0, 1, 0, 1, 0, 0, 0, 0]
b = []
for i in range(len(a)):
if a[i] == 1: b....
42
votes
7
answers
124k
views
Appending item to lists within a list comprehension
I have a list, let's say, a = [[1,2],[3,4],[5,6]]
I want to add the string 'a' to each item in the list a.
When I use:
a = [x.append('a') for x in a]
it returns [None,None,None].
But if I use:
...
41
votes
4
answers
76k
views
call list of function using list comprehension
can I call a list of functions and use list comprehension?
def func1():
return 1
def func2():
return 2
def func3():
return 3
fl = [func1, func2, func3]
fl[0]()
fl[1]()
fl[2]()
I know ...
37
votes
3
answers
8k
views
List comprehension vs generator expression's weird timeit results?
I was answering this question, I preferred generator expression here and used this, which I thought would be faster as generator doesn't need to create the whole list first:
>>> lis=[['a','b'...
35
votes
2
answers
18k
views
Efficiently filtering out 'None' items in a list comprehension in which a function is called
I have a list comprehension that calls a function which potentially returns None.
f = lambda x: x if x < 3 else None
l = [f(x) for x in [1,2,3,4]] # [1, 2, None, None]
I'd like to have the list ...
35
votes
3
answers
42k
views
sum each value in a list of tuples
I have a list of tuples similar to this:
l = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 0)]
I want to create a simple one-liner that will give me the following result:
r = (25, 20) or r = [25, 20] # don'...
34
votes
8
answers
28k
views
List comprehension, check if item is unique
I am trying to write a list comprehension statement that will only add an item if it's not currently contained in the list. Is there a way to check the current items in the list that is currently ...
33
votes
10
answers
117k
views
Forming Bigrams of words in list of sentences with Python
I have a list of sentences:
text = ['cant railway station','citadel hotel',' police stn'].
I need to form bigram pairs and store them in a variable. The problem is that when I do that, I get a pair ...
33
votes
6
answers
73k
views
Python list comprehension for dictionaries in dictionaries?
I just learned about list comprehension, which is a great fast way to get data in a single line of code. But something's bugging me.
In my test I have this kind of dictionaries inside the list:
[{'y'...
33
votes
4
answers
14k
views
Python - Flatten the list of dictionaries
List of dictionaries:
data = [{
'a':{'l':'Apple',
'b':'Milk',
'd':'Meatball'},
'b':{'favourite':'coke',
'dislike':'juice'}
},
...
31
votes
3
answers
128k
views
Transpose a matrix in Python [duplicate]
I'm trying to create a matrix transpose function in Python. A matrix is a two dimensional array, represented as a list of lists of integers. For example, the following is a 2X3 matrix (meaning the ...
31
votes
5
answers
41k
views
Python list comprehensions to create multiple lists [duplicate]
I want to create two lists listOfA and listOfB to store indices of A and B from another list s.
s=['A','B','A','A','A','B','B']
Output should be two lists
listOfA=[0,2,3,4]
listOfB=[1,5,6]
I am ...
31
votes
6
answers
6k
views
Create a list of tuples with adjacent list elements if a condition is true
I am trying to create a list of tuples where the tuple contents are the number 9 and the number before it in the list.
Input List:
myList = [1, 8, 9, 2, 4, 9, 6, 7, 9, 8]
Desired Output:
sets = [...
31
votes
6
answers
22k
views
How to print the progress of a list comprehension in python?
In my method i have to return a list within a list. I would like to have a list comprehension, because of the performance since the list takes about 5 minutes to create.
[[token.text for token in ...
27
votes
1
answer
19k
views
list comprehension in F#
I am trying to do some list comprehension in F#. And I found this.
let evens n =
{ for x in 1 .. n when x % 2 = 0 -> x }
print_any (evens 10)
let squarePoints n =
{ for x in 1 .. n
...
26
votes
5
answers
7k
views
Filter out everything before a condition is met, keep all elements after
I was wondering if there was an easy solution to the the following problem. The problem here is that I want to keep every element occurring inside this list after the initial condition is true. The ...
26
votes
7
answers
105k
views
Python: For each list element apply a function across the list
Given [1,2,3,4,5], how can I do something like
1/1, 1/2, 1/3,1/4,1/5, ...., 3/1,3/2,3/3,3/4,3/5,.... 5/1,5/2,5/3,5/4,5/5
I would like to store all the results, find the minimum, and return the two ...
26
votes
4
answers
7k
views
List comprehension as substitute for reduce() in Python
The following python tutorial says that:
List comprehension is a complete substitute for the lambda function as well as the functions map(), filter() and reduce().
http://python-course.eu/...
25
votes
3
answers
36k
views
Skip elements on a condition based in a list comprehension in python
I have a list List:
List = [-2,9,4,-6,7,0,1,-4]
For numbers less than zero (0) in the list , I would like to skip those numbers and form another list.
Example:-
List = [9,4,7,0,1]
This is a kind ...
24
votes
5
answers
19k
views
Does C# have anything comparable to Python's list comprehensions?
I want to generate a list in C#. I am missing python's list comprehensions. Is there a C# way to create collections on the fly like list comprehensions or generator expressions do in python?
24
votes
1
answer
11k
views
Is there a Scala equivalent to Python's list comprehension?
I'm translating some of my Python code to Scala, and I was wondering if there's an equivalent to Python's list-comprehension:
[x for x in list if x!=somevalue]
Essentially I'm trying to remove ...
24
votes
8
answers
7k
views
Tips for debugging list comprehensions?
Python list comprehensions are nice, but near impossible to debug. You guys have any good tips / tools for debugging them?
24
votes
10
answers
2k
views
Remove any empty list present in the list
I have a list:
i = [[1,2,3,[]],[],[],[],[4,5,[],7]]
I want to remove all the empty list:
[[1,2,3],[4,5,7]]
How can I do this?
Here is my code:
res = [ele for ele in i if ele != []]
23
votes
2
answers
5k
views
Python list() vs list comprehension building speed
This is interesting; list() to force an iterator to get the actual list is so much faster than [x for x in someList] (comprehension).
Is this for real or is my test just too simple?
Below is the code:...
22
votes
6
answers
45k
views
Duplicate elements in a list [duplicate]
I have a list in Python:
l = ['a', 'c', 'e', 'b']
I want to duplicate each element immediately next to the original.
ll = ['a', 'a', 'c', 'c', 'e', 'e', 'b', 'b']
The order of the elements should ...
22
votes
4
answers
12k
views
Nested list to dict
I am trying to create dict by nested list:
groups = [['Group1', 'A', 'B'], ['Group2', 'C', 'D']]
L = [{y:x[0] for y in x if y != x[0]} for x in groups]
d = { k: v for d in L for k, v in d.items()}
...
22
votes
4
answers
16k
views
count occurrences of elements [duplicate]
Counting all elements in a list is a one-liner in Haskell:
count xs = toList (fromListWith (+) [(x, 1) | x <- xs])
Here is an example usage:
*Main> count "haskell scala"
[(' ',1),('a',3),('c',...