python,python-2.7,list-comprehension
I am extending a list called projects to include the project owner from another list. Projects_with_owner has two matches and is returning None. I assume because the element with None is the first match. I'd like to be able to include the one that does have a name if there...

python,syntax,list-comprehension
This question already has an answer here: Converting a loop with an assignment into a comprehension 2 answers Let's say I want to create a list of ints using Python that consists of the cubes of the numbers 1 through 10 only if the cube is evenly divisible by...

python,list-comprehension
I have a dictionary like this: >>> pprint.pprint(d) {'a': ('abc', 'pqr', 'xyz'), 'b': ('abc', 'lmn', 'uvw'), 'c': ('efg', 'xxx', 'yyy')} Now, given a variable x, I want to be able to list all the keys from the dict where the first element in the tuple is equal to x. Hence...

python,list-comprehension
Say I have a list of objects. Maybe its got some ints, some strings, and some floats. What I'd like to do is sort the list so that all ints are moved to the end of the list but no other types are touches, sort of like this... for idx,...

python,dictionary,list-comprehension
I have the following list of dictionaries: ld=[{'a':10,'b':20},{'p':10,'u':100}] I want to write a comprehension like this: [ (k,v) for k,v in [ d.items() for d in ld ] ] basically I want to iterate over dictionaries in the list and get the keys and values of each dict and do...

python,profiling,generator,list-comprehension
Currently I was learning about generators and list comprehension, and messing around with the profiler to see about performance gains stumbled into this cProfile of a sum of prime numbers in a large range using both. I can see that in the generator the :1 genexpr as cumulative time way...

python,list-comprehension
I have a list of sublists like that: posts = [[1, 'text1', 0], [1, 'text2', 0]] and function change_text(text) how can i apply this function only to text elements of each sub-list? i have tried this: posts = [change_text(post[1]) for post in posts] but i got only texts ['changed_text1', 'changed_text2']...

python,list-comprehension
I want to use a list comprehension that returns the filenames of all files in a list of dirs. I've written the following list comprehension which fails since d is not defined at the time of os.listdir(d) on the first iteration. How can I restructure this list comprehension such that...

python,arrays,tuples,list-comprehension,python-3.3
I have (result from a query) my_list = [('a',),('b',),('c',),('g',),('j',)] I want to translate it to ['a','b','c'] What I have so far r = [rs for rs in my_list if rs not in[('g',),('j',)]] This will fetch ('a',),('b',),('c',)...

python,scrapy,list-comprehension,strip
I am using the Scrapy lib. I frequently get lists with '\t' and '\n'. I'm trying to use list comprehensions to strip and remove resulting empty elements, but end up with the empty elements still. Could someone explain how the interpreter is processing the code? It's seems that it is...

python,list-comprehension
Given a list like so: [[1,2,3],[4,5,6],[7,8,9]] I'm trying to get my output to look like this, with using only a list comprehension: 1 2 3 4 5 6 7 8 9 Right now I have this: [print(x,end="") for row in myList for x in row] This only outputs: 1 2...

python,list,python-3.x,list-comprehension
Is there a way to add items to a list conditionally, when defining the list? Here's what I mean: l = [ Obj(1), Obj(2), Separator() if USE_SEPARATORS, Obj(3), Obj(4), Obj(5), Separator() if USE_SEPARATORS, Obj(6) ] Obviously the above code doesn't work, but is there a similar way? Currently I have...

python,python-2.7,list-comprehension
I am trying to extend values to a list if an element in List1 equals an item in List2. I am using extend instead of append because extend is suppose to merge two lists. Instead it seems to be nesting lists. Removing the brackets around y[1],y[2] yields: SyntaxError: Generator expression...

python,list-comprehension
Essentially, I wrote a different set of code that called together a given shop's name and the total price of a grocery list if it was bought there. As tuples use only the first element to compare (unless they are equal) I've set them up so that the total value...

range,list-comprehension,julia-lang
Another newbie question, I find this difference very confusing: it = 1:3 typeof([i^2 for i in 1:3]) # Array{Int64,1} typeof([i^2 for i in it]) # Array{Any,1} why does it matter where the range is defined? typeof([i^2 for i in it::UnitRange{Int64}]) seems to give a hint, as does this discussion. However,...

python,list,python-2.7,python-3.x,list-comprehension
This question already has an answer here: Python list comprehension expensive 1 answer I was wondering why list comprehension is so much faster than appending to a list. I though the difference wasn't expressive, but it is. >>> import timeit >>> timeit.timeit(stmt='''\ t = [] for i in range(10000):...

python,list,dictionary,list-comprehension
I am working on a spatial analysis problem using Python 2.7. I have a dictionary edges representing edges in a graph, where key is the edgeID and the value is the start/end points: {e1: [(12.8254, 55.3880), (12.8343, 55.3920)], e2: [(12.8254, 55.3880), (12.8235, 55.3857)], e3: [(12.2432, 57.1120), (12.2426, 57.1122)]} And I...

python,list-comprehension,nested-lists
I have a list of lists in python looking like this: [['a', 'b'], ['c', 'd']] I want to come up with a string like this: a,b;c,d So the lists should be separated with a ; and the values of the same list should be separated with a , So far...

python,json,list-comprehension
I am trying to generate a list based on this JSON: city_list = [ city for city in metroextractor_cities['regions'][region]['cities'] for region in metroextractor_cities['regions']] Python says the variable region is referenced before assignment: UnboundLocalError: local variable 'region' referenced before assignment I don't really see that. What is wrong with my list...

python,sqlalchemy,list-comprehension
I have a list of record instances returned by SQLAlchemy. While the instances have many attributes, I want a new list with only one of the attributes. The java coder in me says: my_records = query.all() names = [] for my_record in my_records: names.append(my_record.name) ...which works, of course. But What's...

python,python-2.7,list-comprehension
I want to return the items from Project if that project does not appear in my task list, Task. My code only returns everything and in Project. What am I doing wrong? Task = [['Task1','Project1',3],['Task2','Project4',6]] Project = [['Project1', 'Andrew'],['Project2','Bob'],['Project3','Bob']] not_in_list = [item for item in Project if item[0] not in...

python,loops,list-comprehension
How do I replace the following for loops with a more efficient list comprehension or something similar? Numpy and Pandas are not an option as they are not installed on the client system, but perhaps itertools could be useful? n_day_cells = 24*60/240 week_matrix = list() for i in range(7): for...

python,python-2.7,iterator,list-comprehension
The following example shows different behaviour depending on whether the rightmost generator in a list comprehension is a list or an iterator. Specifically, fewer results are generated when using an iterator - I find this behaviour to be very surprising. I'm new to Python so I guess I'm missing something...

python,list-comprehension,nim,nimrod
Since Nim shares a lot of features with Python, i would not be surprised if it implements Python's list comprehension too: string = "Hello 12345 World" numbers = [x for x in string if x.isdigit()] # ['1', '2', '3', '4', '5'] Is this actually possible in Nim? If not, could...

python,list-comprehension
I have come across the following chained list comprehension code in the online book A Programmer's Guide to Data Mining (chapter 8) and it's a bit confusing. First example: self.centroids = [[self.data[i][r] for i in range(1, len(self.data))] for r in random.sample(range(len(self.data[0])), self.k)] Second example: self.centroids = [[sum([self.data[k][i] for i in...

list,haskell,list-comprehension
I want to create a function that given two lists (of floats, but could be anything) gives a list with all the combinations of taking two elements from the first list and putting it in the last and all the combinations of the former putting one of the elements from...

python,html,beautifulsoup,list-comprehension
I've narrowed my HTML down and I want to pull the hrefs from each line IF the content following the a tag is past 2010. What's the best way to do this? I'll post my code first, and then the HTML. Code: links = [STEM_URL + row.a["href"] for row in...

python,list-comprehension,class-method
If you have a class with several methods, for example class A: def a(self): return 1 def b(self): return 2 def c(self): return 3 How could you call a sequence of A's methods on an instance of A? I tried the following >>> foo = A() >>> l = [A.a,...

python,list-comprehension
I have a list of dictionaries and I want to get the list of 2 of the keys in the list. Here is how I do it now: l_id = [d['id1'] for d in l_data] l_id.extend([d['id2'] for d in l_data]) Is there a pythonic way to do the list comprehension...

python,list,if-statement,append,list-comprehension
I am trying to figure out if it is possible to make a list comprehension if you create more than one element of the target list in one step. Lets have a list like this: input_list=['A','B','C/D','E'] and what I want to get in the end is output_list=['A','B','C','D','E']. This is the...

python,list,list-comprehension
I am just trying to understand what happens during list comprehension. Some methods which work on lists 'in-place' don't seem to work when applied in a list comprehension: a = [[1, 2, 3], [4, 5, 6]] i1 = id(a[0]) for i in a: i.reverse() >>> [[3, 2, 1], [6, 5,...

python,iterator,generator,list-comprehension,generator-expression
I have several sampling functions that need to be called for a certain amount of times as in the following instruction: samples = [do_sampling() for _unused in range(n_samples)] I wonder, is there a more compact way to express that statement, especially by avoiding the _unused variable?...

python,algorithm,list,dictionary,list-comprehension
I am trying to create a complete graph in a Python Dictionary in 1 line. But when creating the list comprehension for the values I can not figure out how to specify that the key_value can not appear in the list of values (in graph speak, no self loop). for...

haskell,list-comprehension
I'm trying to write a function group::[(Int, Int)]->[[(Int, Int)]] that would group elements of a list of tuples into subgroups dependant on the first coordinate, ie: group [(1,1),(1,2),(2,1),(2,2),(2,3)] should result in [[(1,1),(1,2)],[(2,1),(2,2),(2,3)]] I'd imagine list comprehension is the way, but I'm a bit stuck.. Could someone provide an advice/solution? PS...

python,python-2.7,tuples,list-comprehension
I got a problem which is: receive a tuple with objects of any type, and separate it into two tuples: the first, with strings only; the second, with numbers only. Alright. The standard algorithm would be something like: def separate(input_tuple): return_tuple = ([],[]) for value in input_tuple: if isinstance(value, str):...

search,list-comprehension,elixir
I am starting my journey with Elixir and am looking for some advice on how best to approach a particular problem. I have a data set that needs to be searched as quickly as possible. The data consists of two numbers that form an enclosed band and some meta data...

python,list,dictionary,list-comprehension
This is my list myList = ['Bob', '5-10', 170, 'Tom', '5-5', 145, 'Bill', '6-5', '215'] I want to make into a dictionary like this. {'Bob': ['5-10', 170], 'Bill': ['6-5', '215'], 'Tom': ['5-5', 145]} I came up with this but it is very ugly and doesn't scale up. def MakeDict(): d...

python,list,list-comprehension
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 being constructed? Here is a brief example: Input { "Stefan" : ["running",...

python,numpy,multidimensional-array,list-comprehension
I am new to NumPy. I have a 2-D NumPy array containing floating point values. I wish to get the index of those elements which are greater than 70 % of a certain value, say t ,in the entire matrix. output = [(1,2),(4,7),(7,1)] meaning arr[1][2], arr[4][7] and arr[7][1] have values...

python,python-2.7,salesforce,list-comprehension,soql
I'm querying Salesforce via the python package, Simple_Salesforce. The results are returned as an OrderdDict. I would like to convert the records to a simple list of lists (although in the sample there is only 1 record). This is very easy to do, except in this example, the field Approval_Date__c...

python,list-comprehension
Suppose loc is a 2d list of characters, I want to join it into a string s. Which of the following code is faster, in general? s = ''.join([''.join(row) for row in loc]) s = ''.join([x for row in loc for x in row]) Thanks!...

python,python-3.x,list-comprehension,set-comprehension
Here's my classmethod for getting all the subclasses recursively: @classmethod def get_subclasses(cls): subclasses = set() for subclass in cls.__subclasses__(): subclasses.add(subclass) subclasses.update(subclass.get_subclasses()) return subclasses Is there a way to make it a one-liner? Something like: return set(subclass.__subclasses__() for subclass in self.__subclasses__()) ...

python,list-comprehension
I'm trying to get a list of all files inside a directory and delete them. I've used the following code and it's working fine. Code: import os file_list=os.listdir(mypath) for x in file_list: os.remove(mypath+"/"+x) But when I try to do it using the list comprehension way, it's giving a syntax error....

python,numpy,list-comprehension
this = rand(100,3,4) for i in range(0,100): for j in range(0,3): for k in range(0,4): if rand()<0.5: this[i,j,k]=0 Where rand is numpy.random.rand Can the above be written in chained list comprehension? Aim: to assign value 0 to each term in "this" (3D matrix) with certain probability(0.5)...

python,list-comprehension
How would I do the following in a list comprehension? asins = [] for item in data['message']['body']['titles']: for format in item['formats']: for offer in format['offers']: asins.append(offer['asin']) ...

python,python-2.7,list-comprehension
I have gone through many blogs regarding python time complexity and posting my doubt: In case of list comprehensions how will the time complexity be analysed? For example: x = [(i,xyz_list.count(i)) for i in xyz_set] where xyz_list = [1,1,1,1,3,3,4,5,3,2,2,4,5,3] and xyz_set = set([1, 2, 3, 4, 5]) So, is the...

list,haskell,append,list-comprehension
So I wrote a function that takes a list of lists as an argument and takes every single element from the first list and appends it to a recursively called function on the list of lists' tail, in result returning all possible combinations of selecting elements from these lists. foo...

python,optimization,lazy-loading,list-comprehension,generator-expression
While refactoring a piece of code, I noticed this: if product_id in [c["id"] for c in self.data.load_products()]: # Do something In turn, load_products() does an SQL query, and for every product: Performs some relatively CPU-costly operations and: Uses yield to return the products one by one to the caller. As...

haskell,list-comprehension
So, been going over some old exams in preparation for my upcoming one and came across this question: Write Haskell code to define ints :: [Int] an infinite list of the following form: [0, 1, -1, 2, -2, 3, -3, 4, -4..] I've been plugging at it for the past...

python,list,list-comprehension
I have a list of tuples, which will be converted to another list which has elements of list type, since each element is a list, we can insert the natural number at the head. Let's put: l = [('c++', 'compiled'), ('python', 'interpreted')] lx = [] for z in xrange(len(l)): y...

python,list-comprehension
Here is an example i'm working with: >>> a = [('The','det'),('beautiful','adj')] >>> d = [y for (x,y) in a] >>> z = [x.lower() for (x,y) in a] >>> final=[] >>> final = zip(d,z) >>> final >>> [('det', 'the'), ('adj', 'beautiful')] This is a good way to work with when working...

python,list,dictionary,list-comprehension
I have this dictionary: primes = {2: True, 3: True, 4: False, 5: True, 6: False, 7: True} And I wanted to create a list with only the pair that are True. It would look like this: [2, 3, 5, 7] So I tried doing it this way: primelist =...

list,function,haskell,list-comprehension,elements
I have [[Integer]] -> [Integer] and want to take the first element of the first sub-list, the second element of the second sub-list and .. the n-th element of the n-th sub-list and so on. I am trying to achieve this using list comprehensions. However, I first drop an incrementing...

python,list-comprehension,itertools
Consider some given sequence and a window length, say the list a = [13 * i + 1 for i in range(24)] (so that In [61]: a Out[61]: [1, 14, 27, 40, ..., 287, 300] ) and window length 3. I'd like to take the sliding window sum of this...

python,list,python-3.x,list-comprehension
Suppose I have a list ['x1_0','x2_1','x3_0'] How can I split the above list into two lists such that the first list contains ['x1','x2','x3'] and the second list [0,1,0]? i.e. ('x1_0') / \ / \ / \ 1st list 2nd list 'x1' 0 Feel free to use as many tools as...

haskell,pattern-matching,list-comprehension
Why does the following attempt to pattern-match in a list comprehension not work? Example: simultaneous substitution of atoms in a term data type. The data type: data Term a = Atom a | Compound (Term a) (Term a) deriving Show The substitution algorithm for atoms in terms (picks the first...

python,for-loop,list-comprehension
I am trying to convert this list comprehension: cfg = [] ... cfg = [conf + function1(s) for s in cfg] To a regular multiline for, because it is necessary to include more things into it: cfg = [] ... for s in cfg: cfg.append(conf + function1(s)) But in the...

python,dictionary,list-comprehension,dictionary-comprehension
Having trouble turning these loops into a dictionary comprehension - it might be impossible. The general idea is that I have a dictionary of excludes that looks like this: excludes = { "thing1": ["name", "address"], "thing2": ["username"] } Then I have a larger dictionary that I want to "clean" using...

python,list-comprehension
I am using comprehensive lists in my config file like this object1 = { sq = @([x**2 for x in range(1,10)]) } I load the object using PyOptionTree. It works fine. But, I want to use another variable in this equation now. Something like this object1 = { y =...

python,list,set,list-comprehension
I'm getting started with Python and currently learning about list comprehensions so this may sound really strange. Question: Is it possible to use list comprehension to create a list of elements in t and s without duplicates? Sort of like union of two sets but using lists instead...? I use...

python,python-3.x,scope,list-comprehension,python-2.x
I can't find anywhere that defines this behaviour: if [x for x in [0, 1, -1] if x > 0]: val = x How safe is this code? Will val always be assigned to the last element in the list if any element in the list is greater than 0?...

python,python-2.7,list-comprehension
I would like to do list comprehension only on the second and third element of each sub-list. I've been able to do this, but I lose the first element. I know I could do this pretty easily with a for loop, but I'd like to be pythonic (idiomatic python) and...

python,list,python-3.x,list-comprehension,generator-expression
In Python 3, is a list comprehension simply syntactic sugar for a generator expression fed into the list function? e.g. is the following code: squares = [x**2 for x in range(1000)] actually converted in the background into the following? squares = list(x**2 for x in range(1000)) I know the output...

python,python-2.7,list-comprehension
I would like to return a item in a list if certain conditions are met. One condition is that my the Project is "Project A", but the other is that t[1] is not None for all sublists that contain "Project A". The code I have works, but it seems inefficient....

python,python-2.7,dictionary,list-comprehension,key-value
I have a dictionary of keys of dates. Each date has a key:value pair of a project and a list of days. I would like to add an average metric to each date key, while removing outliers above 6. My code is close, but produces some screwy results. import numpy...

python,list,list-comprehension
Suppose I have a list of numbers I'd like to increment and I'm only interested in the incremented values, not the original ones afterwards. What is the most pythonic way to do it in situ, without copying the list? Does a = [1, 2, 3] a = [i+1 for i...

haskell,recursion,list-comprehension
This is a small part of a tutorial assignment where we have been asked to define a function firstly using a list comprehension and then using explicit recursion. Using a list comprehension, define a function duplicated :: Eq a => a -­‐> [a] -­‐> Bool that takes a list element and...

python,list-comprehension
I have a running python script that reads in a file of phone numbers. Some of these phone numbers are invalid. import re def IsValidNumber(number, pattern): isMatch = re.search(pattern, number) if isMatch is not None: return number numbers = [line.strip() for line in open('..\\phoneNumbers.txt', 'r')] Then I use another list...

python,dictionary,list-comprehension
I'm trying to get my head around list comprehensions and I can understand the basics of how they work but I get the feeling I should be able to do something with my code here that I just can't seem to get working. Given a dictionary: {2: {11}, 9: {11,...

python,list-comprehension
I was looking at itertools.product, and in the explanation is a function meant to explain how the function kinda works. It looks like all the magic happens here, in a loop through the lists: result = [x+[y] for x in result for y in list]. So I decided to try...

python,list-comprehension
This question already has an answer here: Is it possible to implement a Python for range loop without an iterator variable? 14 answers I wonder if there is a way to use e.g. a list comprehension without an iteration variable if I do not need it? For example, in...

python,list-comprehension
Consider the following code: a = [... for i in input] i = a.index(f(a)) I'm wondering whether I could be able to do an one-liner. Obvious try is: i = [... for i in input].index(f([... for i in input])) But this solution requires list to be generated twice. Not-so-obvious try...

python,list,dictionary,list-comprehension
So I have this list that looks like this: ['One', 'Two', 'Three', 'Four'] ['Five', 'Six', 'Seven'] so, a list with 2 elements lst = [['One', 'Two', 'Three', 'Four'], ['Five', 'Six', 'Seven']] And then I have also a dictionary that I declared like this: numberDict = dict() numberDict["One"] = "First" numberDict["Two"]...

python,list-comprehension
Title is obviously confusing. Example: >>>a = [b if len(b) != 0 else 'lambda'] I want to create this variable only if the statement is met. I don't want it to even exist otherwise. So how come >>>a = [b if len(b) != 0] gives a SyntaxError? Is there a...

python,list,list-comprehension,behavior
I was looking at a stackoverflow question (if else in a list comprehension) and decided to try the following line [ a if a else "Exception" for a in range(10) ], and got the following list [ "Exception", 1, 2, 3, 4, 5, 6, 7, 8, 9 ] as an...

python,list,list-comprehension
I am trying to turn any floating point number in the list 'codes' to an int. codes = [890.0,'JFR'] codes = [int(c) for c in codes] I am getting the error: ValueError: invalid literal for int() with base 10: 'JFR' What I want the list 'codes' to be is: [890,'JFR']...

python,list-comprehension,dictionary-comprehension
I'm currently using list comprehension inside dictionary comprehension to detect changes between 2 dictionaries with lists as values. The code looks something like this: detectedChanges = {table: [field for field in tableDict[table] if field not in fieldBlackList] for table in modifiedTableDict if table not in tableBlackList} This will create a...

haskell,list-comprehension
I want to make function which returns list of multiplied elements from each pair from list of pairs. For example: >product [1,2] [3,4] [3,8] I want to do this using list comprehension. I tried something like this: product :: Num a => [a] -> [a] -> [a] product xs ys...

javascript,python,list-comprehension
For example, in Python we have such a convenient tool — instead of writing like values = [1,2,3,4,5] altered_values = [] for v in values: altered_values.append(v*25) We could just write altered_values = [v*25 for v in values] Are such one-liners possible in Javascript?...

python,list,list-comprehension
For example if I have a selection set K K = ['a','b','c'] and a length N N = 4 I want to return all possible: ['a','a','a','a'] ['a','a','a','b'] ['a','a','a','c'] ['a','a','b','a'] ... ['c','c','c','c'] I can do it with recursion but it is not interesting. Is there a more Pythonic way?...

python,list-comprehension,iterable-unpacking
If I have nums_and_words = [(1, 'one'), (2, 'two'), (3, 'three')] and would like nums = [1, 2, 3] words= ['one', 'two', 'three'] How would I do that in a Pythonic way? It took me a minute to realize why the following doesn't work nums, words = [(el[0], el[1]) for...

python,list-comprehension
I am currently playing about with Project Euler problem 53 in Python. The solution is trivially simple but involved the following list comprehension: [scipy.misc.comb(n, r, exact=True) for n in range(1,maxn+1) for r in range(0,n+1) if scipy.misc.comb(n, r, exact=True) > threshold] My concern is though that the scipy.misc.comb() function would be...