FAQ Database Discussion Community


Do variables defined inside list comprehensions leak into the enclosing scope?

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

Handling tuples as values within a dictionary (in list comprehensions)

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

Concatenating certain parts of a list. Removing spaces.

python,list,concatenation,list-comprehension,spaces
I have a list of names split up letter by letter, I would like to concatenate the individual names together. This is what I currently have: ['S', 't', 'u', 'a', 'r', 't', ' ', 'S', 't', 'e', 'v', 'e', ' ', 'A', 'n', 'd', 'r', 'e', 'w', ' ', 'L',...

Can one use list comprehension derivatives in its methods?

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

List appending in Haskell

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

How to change n-th element in list of lists with python list comprehensions?

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

Haskell: Are list comprehensions higher order functions?

list,haskell,functional-programming,list-comprehension
I have an assignment where we are not supposed to use any higher order functions, could a list comprehension be classified as a higher order function?

return items from one list if not in the other

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

HTML list comprehension issue while using Beautiful Soup w Python

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

Sorted by type in Python

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

Are generator expressions doing less work compared to list comprehensions?

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

Pattern matching in case expressions/list comprehensions

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 Tuple Unpacking

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

Is this list comprehension pythonic enough? [duplicate]

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

How can I check if a list in a list comprehension inside a dictionary comprehension is empty?

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

max value if no values are none - python

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

Adding key for average values in nested dictionary lists

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

Double for loop to Python list comprehension

python,list,list-comprehension
I have the following (simplified structure): class Wafer: def __init__(self, df): self.dose_fields = df class Data: def __init__(self, add_zero): self.wafers = [] self.wafers.append(Wafer([1.0, 1.5])) self.wafers.append(Wafer([2.0, 2.0])) self.wafers.append(Wafer([3.0, 3.5])) self.wafers.append(Wafer([4.0, 4.5])) if add_zero: self.wafers.append(Wafer([5.0, 0.0])) I want to have a function that returns False when there is a zero in one...

Python 2D NumPy array comprehension

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 list comprehension not working for function parameters

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

List of dictionaries with comprehension in python

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

Using List Comprehension with Dictionaries in Python

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

how can I turn this list comprehension into for loops

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

Perform list of class methods on instance of class

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. Alternative/Better way to write this code?

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

List of lists, take next element

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

Get a list of N items with K selections for each element?

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

Most efficient interval type search in Elixir

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

List comprehension variable referenced before assigned

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 - List comprehension - if statement without else possible?

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

Iterate two lists Haskell

loops,haskell,list-comprehension
I have this function: applyRel :: (Eq k) => k -> (BinaryRelation k v) -> [v] applyRel key list = [ v | (k,v)<-list, key==k] and it takes a string, k and returns all v's with the given k: applyRel "bar" bar_stuff would output ["mitzva", "stool", "tender", "keeper"] And it...

Join 2d list of characters into a string

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

how to get only the first element of a touple list into an array

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',)...

How do i check the time complexity of a comprehension

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

Convert only floating point numbers to int in list python

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

Generators vs List Comprehension performance in Python

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

More Compact List Comprehension Where Iteration Variable is Unused

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

Generating Infinite List in Haskell

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

List comprehension inside dictionary comprehension - scope

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

Set union, List Comprehensions

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

How to understand the list comprehensions in making list in python?

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

Haskell grouping list elements by fst

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

list to dictionary python

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

List Comprehension Nested Loop, Multiple Operations

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

Replace for-loop across week with list comprehension

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

Why is list comprehension so faster? [duplicate]

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):...

List comprehension doing duplicate work

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

List comprehension, check if item is unique

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 List Comprehendion: Elegantly strip and remove empty elements in list

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 nested list comprehension string concatenation

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

Using list comprehension for a For/if/else loop

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

Building OCaml code that uses list comprehension

ocaml,list-comprehension,ocaml-batteries
From this SO question: List Comprehension in Ocaml?, I could install the comprehension package with opam install pa_comprehension, and use the package in toplevel REPL. # #require "pa_comprehension";; # open Batteries;; # [? 2 * x | x <- 0 -- max_int ; x * x > 3 ?];; -...

Changing values of a list by getting them from a dictionary (Python)

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

How to expand a string within a string in python?

python,string,dictionary,concatenation,list-comprehension
I have a string that looks like this: 1 | xxx | xxx | xxx | yyy*a*b*c | xxx I want to expand the yyy*a*b*c part so that the string looks like this: 1 | xxx | xxx | xxx | yyya | yyyb | yyyc | xxx I actually...

Are list comprehensions syntactic sugar for `list(generator expression)` in Python 3?

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

Convert a list comprehension loop into a regular for loop without creating an infinite loop

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

List Comprehension of certain elements on a nested list

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

Nim equivalent of Python's list comprehension

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

How do you plot a graph consisting of extracted entries from a nested list?

plot,list-comprehension,python-3.4,nested-lists
I have a nested list such that; nested_list = [[4, 3, 0], [6, 8, 7], [3, 1, 8], [2, 1, 3], [9, 9, 3], ...] which has 100 entries. I need to plot a graph of all the first elements of each sub-list where Sub_List_1 = [4, 6, 3, 2,...

Python dictionary comprehension with nested for

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

Condense multiple for loops into list comprehension

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

extending a list to a list

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

best way to do list comprehension matching when there are multiple matches

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

Unroll Python chained list comprehension

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

Swift List Product

swift,list-comprehension
Given two lists in Swift: let rows = ["a", "b", "c"] let cols = ["1", "2", "3"] Is it possible to combine them using list comprehension to produce the following: squares = ["a1", "a2", "a3", "b1", "b2", "b3", "c1", "c2", "c3"] Obviously, it can be done using a "for loop"...

Python applying a list of functions to a list of items including None values

python,list,list-comprehension
If I have a list of data-items where I'd like to convert type for example: row = (u'2013-13-04 00:00:00', u'P1', u'BRT64510', u'CHUCKLES MOTOR COMPANY', u'123', None, u'2345', u'100000', u'150000000', None, u'100000', None, u'123345', u'1234567', u'122445', None) and a list of conversion formulae for example: import datetime dt = datetime.datetime st...

Cyclical Sliding Window Iteration

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

Elements missing when iterator used in a list comprehension

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 with adding more elements in one go

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

How to divide a tuple into two in pythonic way

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):...

Is there a way to “one-line” this using list/set comprehension?

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 - need elements skipped combinations

python,list,list-comprehension
For this input list [0, 1, 2, 3, 4, 5] I need this output [[0, 2], [0, 3], [0, 4], [0, 5], [1, 3], [1, 4], [1, 5], [2, 4], [2, 5], [3, 5], [0, 2, 3], [0, 3, 4], [0, 4, 5], [1, 3, 4], [1, 4, 5], [2,...

Unexpected replacement of zero in Python list comprehension

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

Why a generator object is obtained instead of a list

python,list,list-comprehension
Using Python 3.4, I have the following JSON mylist = [ { "mdata": [ { "url" : "http://fake1001/Standard", "fmt" : "Standard" }, { "url" : "http://fake1001/Thumb", "fmt" : "Thumb" } ] }, { "mdata": [ { "url" : "http://fake1002/Standard", "fmt" : "Standard" }, { "url" : "http://fake1002/Large", "fmt" : "Large"...

Uncool List Comprehension

python,excel,python-3.x,list-comprehension,xlwings
Here's my function for finding the location of specific values on an Excel sheet. from xlwings import Workbook, Range workbook = Workbook('workbook location') def get_data_locations(): """ Find data locations from the first sheet in document. """ first_sheet = Range('Sheet1', 'A1:Z200').value coordinates = [] for x in range(len(first_sheet)): coordinate_pair = [[x...

Elegant and cheap way to transform lists in python

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

Merge multiple list comprehensions

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

comprehension over external range loses output type

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

Conditionally add items to a list when defining the list?

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

List Comprehension for Ordered Nested Dictionary to Python List

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

Chained list comprehension in python

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

What's the pythonic idiom for making a simple list out of a list of instances?

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

Explicit Recursion for Determining If Duplicates in Haskell

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

single list comprehension to unpack nested dictionary

python,list-comprehension
I'd like to turn this a = {'a': {'b': 'b aw', 'c': 'c aw'}, 'b': {'b': 'b2 aw', 'c': 'c2 aw'}, 'c': {}} into this ['b aw', 'c aw', 'b2 aw', 'c2 aw'] with a list comprehension. I think I need some way to make this expression 'legal': a2 =...

Maximum recursion depth error, somehow related to list comprehension notation

python,recursion,runtime-error,list-comprehension
I'm completely new to Python and I'm stumped by the following. As part of a crash course, I've written a quicksort function using list comprehensions, as follows: data = [78,3,3526,-12244,9,2,8,6,-84,3642,1,-1234, 234, 23, -1, -11, 34] pivot = data[0] def quicksort(lst): if len(lst) <= 1: return lst lessThanPivot = [x for...

Use list comprehension without iteration variable [duplicate]

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

how to insert into python nested list

python,list,list-comprehension
I want to insert an item into a list inside a list. I'm wondering if someone can show me. list5 = [[], [(1,2,3,4), 2, 5]] print("1. list5", list5) list5.insert(0, (2,5,6,8)) print("2. list5", list5) Output: 1. list5 [[], [(1, 2, 3, 4), 2, 5]] 2. list5 [(2, 5, 6, 8), [],...

Optimizing two-dimensional arrays

python,arrays,optimization,multidimensional-array,list-comprehension
I'm coding in Python 2.7. I have two 2D arrays of coordinate tuples. array1 = [[[00_RA,00_DEC] [01_RA,01_DEC] ... [0N_RA,0N_DEC]] [[10_RA,10_DEC] [11_RA,11_DEC] ... [1N_RA,1N_DEC]] ... [[M0_RA,M0_DEC] [M1_RA,M1_DEC] ... [MN_RA,MN_DEC]]] array2 = [[[00_ra,00_dec] [01_ra,01_dec] ... [0n_ra,0n_dec]] [[10_ra,10_dec] [11_ra,11_dec] ... [1n_ra,1n_dec]] ... [[m0_ra,m0_dec] [m1_ra,m1_dec] ... [mn_ra,mn_dec]]] I want to find the coordinates of...

List comprehesion using a dictionary

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

Python: Accessing a variable by a comprehensive list in a config file

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

How to multiply two elements of each pair from list of pairs - Haskell

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

how is die Interpretation of this comprehension list

python-2.7,list-comprehension
How can I understand this line? O = [[[-1 for i in range(int(o[0][1]))] for k in range(int(i[0]))] for i in o] ...

How do I split the lists in python

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

Something like list comprehension in JS?

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

Speed up finding matches between two dictionaries (Python)

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

Haskell list comprehension compilation error

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

How to combine the letters in two strings in haskell

string,haskell,char,list-comprehension
I am learning Haskell and following the guide on http://learnyouahaskell.com/starting-out. I am at the point where it is shown: ghci> let nouns = ["hobo","frog","pope"] ghci> let adjectives = ["lazy","grouchy","scheming"] ghci> [adjective ++ " " ++ noun | adjective <- adjectives, noun <- nouns] ["lazy hobo","lazy frog","lazy pope","grouchy hobo","grouchy frog", "grouchy...

List comprehension with repeated computation

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

List comprehension and in place methods

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

Using enumurate value of second for in list comprehension

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