-1

I'm struggling to get an understanding of how Python treats for loops that come after variables. I think it might have something to do with iterables/iterators in Python, but I'm not sure I really understand the usage. Basically in the following code I understand the math of why it works to produces the combinations of the variables, but I don't get how this is a valid way to create a list. In my experience with other languages, for loops always cone before the expressions and are properly nested when there is more than one.

temp = [('CH', 'AG', 'ME', 'GS')]
[(temp[i],temp[j]) for i in range(len(temp)) for j in range(i+1, len(temp))]

#produces:[('CH', 'AG'), ('CH', 'ME'), ('CH', 'GS'),
#('AG', 'ME'),('AG', 'GS')('ME', 'GS')]

Can anyone explain what's going on here?

martineau
  • 119,623
  • 25
  • 170
  • 301
JoeTheShmoe
  • 433
  • 6
  • 13
  • 2
    It's a list comprehension. There are lots of references/tutorials online about them. – Robin Zigmond Oct 08 '18 at 17:22
  • Complexity-wise it will be similar to other languages. You should look for list comprehension – mad_ Oct 08 '18 at 17:23
  • 1
    I would start with the official Python documentation on [list comprehensions](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions). – Daniel Pryden Oct 08 '18 at 17:23
  • I'm a bit late though but let me add one thing that list comprehension is a bit fast than trivial for loop. – Anonymous Oct 08 '18 at 17:24

1 Answers1

1

The inline for loops end up nested within each other. If you were to write it out, you'd do it like this:

temp = [('CH', 'AG', 'ME', 'GS')]
ret = []
for i in range(len(temp)):
    for j in range(i+1, len(temp)):
        ret.append((temp[i], temp[j]))

Basically, if you have multiple inline for loops, they get nested such that the first one you declare is the outer loop and the last one you declare is the inner loop. See this Stackoverflow question for a more detailed explanation.

Python allows these "list comprehensions" as a shorthand, because it's easier and more "pythonic" (for a definition of what this means, open a python console and type import this; the relevant platitude here is "Flat is better than nested"). You see how you can create the entire list in one line, in a very simple-to-understand manner, rather than having to write out four lines and build up the array slowly step-by-step like you'd have to in most other languages.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
  • Thank you! I didn't know what to search in SO because I've never come across these before and didn't know what they were called, appreciate the help! – JoeTheShmoe Oct 08 '18 at 17:37