1

A few weeks ago I learned about list comprehensions, and ever since then I have been using them constantly. In fact I have not altered or built a single list since I learned about list comprehensions, and I am wondering if that is a problem. I have a few concerns about list comprehensions...

  1. Firstly, are they faster?
  2. Secondly, is they are faster, is there ever a case to use a for loop when dealing with lists.

For example, I need to create a specific list that only has certain numbers in it. It's hard to explain why certain numbers are allowed in this list I'm creating, so I won't explain it because it is not that significant.

For this code I will present the two ways I have solved it and I want to know which is faster and a more "Pythonic" solution, and I also am wondering if there is a better way to solve this.

Solution 1:

coordinateShell = [0, 1, 2, 3, 16, 17, 18, 19]
outerShell = [(xCoordinate, yCoordinate) for xCoordinate in range(20) for yCoordinate in range(20)
              if xCoordinate in coordinateShell or yCoordinate in coordinateShell]

Solution 2:

coordinateShell = [0, 1, 2, 3, 16, 17, 18, 19]
outerShell = []
for xCoordinate in range(20):
    for yCoordinate in range(20):
        if xCoordinate in coordinateShell or yCoordinate in coordinateShell:
            outerShell.append((xCoordinate, yCoordinate))

Thank you for any help! It is greatly appreciated.

TheBlarson
  • 11
  • 1
  • Have a look [here](https://stackoverflow.com/questions/16341775/what-is-the-advantage-of-a-list-comprehension-over-a-for-loop) and [here](https://stackoverflow.com/questions/14124610/python-list-comprehension-expensive). – Roald Feb 27 '18 at 14:05
  • 1
    Possible duplicate of [What is the advantage of a list comprehension over a for loop?](https://stackoverflow.com/questions/16341775/what-is-the-advantage-of-a-list-comprehension-over-a-for-loop) – Roald Feb 27 '18 at 14:06

1 Answers1

0

1.list comprehension will always be faster

2.if your list has certain numbers only and you know them then lookup table is the fastest way to do anything further

classicdude7
  • 903
  • 1
  • 6
  • 23