list-comprehension

Why don't Python's list comprehensions make copies of arguments so actual objects can't be mutated?

Maybe I've been drinking too much of the functional programming Kool Aid, but this behavior of list comprehensions seems like a bad design choice: >>> d = [1, 2, 3, 4, 5] >>> [d.pop() for _ in range(len(d))] [5, 4, 3, 2, 1] >>> d [] Why is d not copied, and then the copied lexically-scoped version not mutated (and then lost)? The poin...

Why doesn't Pylint like built-in functions?

Hi, I have a line like this: filter(lambda x: x == 1, [1, 1, 2]) Pylint is showing a warning: W: 3: Used builtin function 'filter' Why is that? is a list comprehension the recommended method? Of course I can rewrite this like this: [x for x in [1, 1, 2] if x == 1] And I get no warnings, but I was wondering if there's a PEP fo...

Overloading List Comprehension Behavior?

I'm tasked with creating a model of a cage of hardware. Each cage contains N slots, each slot may or may not contain a card. I would like to model the cage using a list. Each list index would correspond to the slot number. cards[0].name="Card 0", etc. This would allow my users to query the model via simple list comprehensions. For e...

Python: find sequential change in one member of list pairs, report other

There must be a simpler, more pythonic way of doing this. Given this list of pairs: pp = [('a',1),('b',1),('c',1),('d',2),('e',2)] How do I most easily find the first item in adjacent pairs where the second item changes (here, from 1 to 2). Thus I'm looking for ['c','d']. Assume there will only be one change in pair[1] for the entir...

Nested For Loops Using List Comprehension

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 comprehension. I've tried many ways, but have never managed to get it. Does anyone know how to do this? ...

Convert function to single line list comprehension

Is it possible to convert this function, list comprehension combination into a single list comprehension (so that keep is not needed)? def keep(list, i, big): for small in list[i+1:]: if 0 == big % small: return False return True multiples[:] = [n for i,n in enumerate(multiples) if keep(multiples, i, n)] ...

Haskell generalizing problem (involving list comprehensions)

Let's say I want to know all the points on a (x, y) plane that are in the rectangle has. I can calculate that using List Comprehensions, this way: let myFun2D = [(x, y) | x <- [0..2], y <- [0..2]] Now, if I want to accomplish the same for a (x, y, z) space, I can go the same way and do: let myFun3D = [(x, y, z) | x <- [0..2], y <- [...

Python: Advanced Nested List Comprehension Syntax

I was playing around with list comprehensions to get a better understanding of them and I ran into some unexpected output that I am not able to explain. I haven't found this question asked before, but if it /is/ a repeat question, I apologize. I was essentially trying to write a generator which generated generators. A simple generator t...

'else' statement in list comprehensions

I've got a variable that could either be a string or a tuple (I don't know ahead of time) and I need to work with it as a list. Essentially, I want to transform the following into a list comprehension. variable = 'id' final = [] if isinstance(variable, str): final.append(variable) elif isinstance(variable, tuple): final = list(...

Fastest way to convert an iterator to a list

Having an iterator object, is there something faster, better or more correct than a list comprehension to get a list of the objects returned by the iterator? user_list = [user for user in user_iterator] ...

Piecewise list comprehensions in python

What is the easiest/most elegant way to do the following in python: def piecewiseProperty(aList): result = [] valueTrue = 50 valueFalse = 10 for x in aList: if hasProperty(x): result.append(valueTrue) else result.append(valueFalse) return result where hasProperty is some fu...

Does this have function have to use reduce() or is there a more pythonic way?

If I have a value, and a list of additional terms I want multiplied to the value: n = 10 terms = [1,2,3,4] Is it possible to use a list comprehension to do something like this: n *= (term for term in terms) #not working... Or is the only way: n *= reduce(lambda x,y: x*y, terms) This is on Python 2.6.2. Thanks! ...

Omit iterator in list comprehension?

Is there a more elegant way to write the following piece of Python? [foo() for i in range(10)] I want to accumulate the results of foo() in a list, but I don't need the iterator i. ...

list.extend and list comprehension

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 comprehension? a = [['a',2], ['b',2], ['c',1]] [[x[0]]*x[1] for x in a] Result [['a', 'a'], ['b', 'b'], ['c']] But I need this one ['a', 'a...

Python's list comprehension vs .NET LINQ

The following simple LINQ code string[] words = { "hello", "wonderful", "linq", "beautiful", "world" }; // Get only short words var shortWords = from word in words where word.Length <= 5 select word; // Print each word out shortWords.Dump(); can be translated into python using list comprehension as follows. words = ["hello",...

Repeating elements in list comprehension

I have this list comprehension: [[x,x] for x in range(3)] which results in this list: [[0, 0], [1, 1], [2, 2]] but what I want is this list: [0, 0, 1, 1, 2, 2] What's the easiest to way to generate this list? ...

List Comprehension in Nested Lists

Hi all, I have a list like [["foo", ["a", "b", "c"]], ["bar", ["a", "b", "f"]]] and I'm wanting to split it out so I can get a count of the total number of As, Bs, etc. but I'm new to Python and having a bit of a time of it. I'm using [lx for lx in [li[1] for li in fieldlist if li[1]]] to try and get a list with all of the items in th...

Python - removing items from lists

# I have 3 lists: L1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] L2 = [4, 7, 8] L3 = [5, 2, 9] # I want to create another that is L1 minus L2's memebers and L3's memebers, so: L4 = (L1 - L2) - L3 # Of course this isn't going to work I'm wondering, what is the "correct" way to do this. I can do it many different ways, but Python's style guide says t...

Python - functions being called inside list bracket. How does it work?

I was looking for an algorithm to replace some content inside a list with another. For instance, changing all the '0' with 'X'. I found this piece of code, which works: list = ['X' if coord == '0' else coord for coord in printready] What I would like to know is exactly why this works (I understand the logic in the code, just not why...

Efficiently computing size of filtered list

I would like to efficiently compute the size of a filtered list, i.e., I don't want to keep the whole filtered list in memory, I just want to get its size. Is there a more "pythonic" way than computing the size using a for-loop? For example: my_list = [1,2,3,4] # this loads the entire **filtered** list in memory size_of_filtered_list ...