I have been recently introduced to list comprehensions, however, I am not certain I understand them completely.
So, I did a quick search through the docs and google. I found the docs section over data structures.
https://docs.python.org/2/tutorial/datastructures.html
While that gives me an idea with how they work, call me strange, I want to have a more mature understanding of how they operate.
Here is an example from the docs:
>>>[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
Correct me if I am wrong, but this is how I understand how the list is evaluating.
- It looks like the list comprehension evaluates from left to right.
- This comprehension introduces X and Y.
- Then defines X and Y by the lists and evaluates based on position in list as well as the if condition.
- Due to X being assigned as the first variable, like the outside of a nested for loop, it is called first and iterated against Y's list.
- The if condition makes it so the comprehension only produces pairs that are not similar as X iterates through Y's list.
Please correct me if my understanding is incorrect. I welcome more complex examples for comprehensions.