In Python, is there a concise way to use a list comprehension with multiple iterators?

Basically, I would like to build a list comprehension over the "cartesian product" of two iterators. Think about the following Haskell code:

[(i,j) | i <- [1,2], j <- [1..4]]

which yields

[(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4)]

Can I obtain a similar behavior in Python in a concise way?


Asked by: Walter334 | Posted: 27-01-2022






Answer 1

Are you asking about this?

[ (i,j) for i in range(1,3) for j in range(1,5) ]

Answered by: Alford271 | Posted: 28-02-2022



Answer 2

Cartesian product is in the itertools module (in 2.6).

>>> import itertools
>>> list(itertools.product(range(1, 3), range(1, 5)))
[(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4)]

Answered by: Max386 | Posted: 28-02-2022



Answer 3

Fun fact about the nested comprehension: it mimics nested "for" loops, so the inner ones can use values from outer ones. This isn't useful in the cartesian product case, but good to know. For example:

[ (i,j) for i in range(10) for j in range(i) ] 

generates all pairs (i,j) where 0>=i>j>10.

Answered by: Lily178 | Posted: 28-02-2022



Answer 4

This seems to do what you describe:

[[a,b] for a in range(1,3) for b in range(1,5)]

UPDATE: Drat! Should have reloaded the page to see S.Lott's answer before posting. Hmmm... what to do for a little value-add? Perhaps a short testimony to the usefulness of interactive mode with Python.

I come most recently from a background with Perl so with issues like this I find it very helpful to type "python" at the command line and drop into interactive mode and just a)start trying things, and b)refine the niceties by hitting up-arrow and adjusting my previous attempt until I get what I want. Any time I'm hazy on some keyword, help is at hand. Just type: help("some_keyword"), read the brief summary, then hit "Q" and I'm back on line in direct conversation with the python interpreter.

Recommended if you are a beginner and not using it.

Answered by: Fiona935 | Posted: 28-02-2022



Similar questions

python - Alias in list comprehension and iterators

Suppose I have something like: for e in some_list: fct(e.my_first_property, e. e.my_second_property) fct2(e.my_first_property) That's a bit repetitive to write, so I could use for e in some_list: p1 = e.my_first_property p2 = e.my_second_property fct(p1, p2) fct2(p1) Still a bit lengthy. So I wonder whether there is some syntax that...


python - Why results of map() and list comprehension are different?

This question already has answers here:


python: list comprehension tactics

I'm looking to take a string and create a list of strings that build up the original string. e.g.: "asdf" =&gt; ["a", "as", "asd", "asdf"] I'm sure there's a "pythonic" way to do it; I think I'm just losing my mind. What's the best way to get this done?


How to make a list comprehension with the group() method in python?

I'm trying to write a little script to clean my directories. In fact I have: pattern = re.compile(format[i]) ... current_f.append(pattern.search(str(ls))) and I want to use a list comprehension but when I try: In [25]: [i for i in current_f.group(0)] I get: AttributeError: 'list' object has no attribute 'group' So how to m...


Python list comprehension - access last created element?

Is it possible to access the previous element generated in a list comprehension. I am working on some toy encryption stuff. Given the key as an arbitrarily large integer, an initialization value, and a list of elements as the message to encrypt. I need to xor each element with the previous ciphered element and the key. The following loop would do. previous = initialization_value cipher = [] for e...


heap - Does Python's heapify() not play well with list comprehension and slicing?

I found an interesting bug in a program that I implemented somewhat lazily, and wondered if I'm comprehending it correctly. The short version is that Python's heapq implementation doesn't actually order a list, it merely groks the list in a heap-centric way. Specifically, I was expecting heapify() to result in an ord...


list comprehension - One liner to replicate lines coming from a file (Python)

I have a regular list comprehension to load all lines of a file in a list f = open('file') try: self._raw = [L.rstrip('\n') for L in f] finally: f.close() Now I'd like to insert in the list each line 'n' times on the fly. How to do it inside the list comprehension ? Tnx


python - Why does list comprehension using a zip object results in an empty list?

f = lambda x : 2*x g = lambda x : x ** 2 h = lambda x : x ** x funcTriple = ( f, g, h ) myZip = ( zip ( funcTriple, (1, 3, 5) ) ) k = lambda pair : pair[0](pair[1]) # Why do Output # 1 (2, 9, 3125) and Output # 2 ( [ ] ) differ? print ("\n\nOutput # 1: for pair in myZip: k(pair) ...") for pair in myZip : print ( k(pair) ) print ("\n\nOutput # 2: [ k(pair) for pair in myZip ] ...") print ( [ k(pair) for pai...


python - How to walk up a linked-list using a list comprehension?

I've been trying to think of a way to traverse a hierarchical structure, like a linked list, using a list expression, but haven't come up with anything that seems to work. Basically, I want to convert this code: p = self.parent names = [] while p: names.append(p.name) p = p.parent print ".".join(names) into a one-liner like: print ".".join( [o.name for o in &lt;...


Perl equivalent of (Python-) list comprehension

I'm looking for ways to express this Python snippet in Perl: data = {"A": None, "B": "yes", "C": None} key_list = [k for k in data if data[k]] # in this case the same as filter(lambda k: data[k], data) but let's ignore that So looking at it one way, I just want the keys where the values are None or undef. Looking at it another way, what I want is the concise perl equiva...


python - Double Iteration in List Comprehension

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 comprehensions. My question is: Can one iterator in the comprehension refer to the other? In other words: Could I have something like this: [x for x in a for a in b] ...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top