Can Anyone Quickly Explain the Basics of List Comprehension Please?
Python list function or list comprehension - Stack Overflow
Does anyone else hate list comprehension?
I don't understand list comprehensions using if else statements.
Videos
Even Chat-GPT and my dog can't explain it right. I think I might be unintelligent.
There is a slight bit of difference in their performance as can be seen from the following:
squares1 = [x**2 for x in range(1, 11)]
3.07 µs ± 70 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
squares2 = list(x**2 for x in range(1, 11))
3.65 µs ± 35.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
this can primarily be because in case 1 you are iterating and generating values for the list at the same time.
In case 2 you are generating values while iterating and then at the end of it converting the same to a list and this is then stored as a given variable.
I way I see it, first program directly initializes squares1 as a list through list comprehension.
The other one first creates a generator class object and then converts it into a list. I think first approach is more efficient.
There are little differences between lists and generators but as per my knowledge and experience lists do the job faster and generators do it lazily yielding single result for every iteration. For most of your tasks, I'd recommend opting for lists.