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...
- Firstly, are they faster?
- 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.