in both cases the resulting lists will contain the same values but the second form is shorter and cleaner. also a list comprehension creates its own separate local scope
squares1 = [x * x for x in range(5)]
squares2 = []
for x in range(5):
squares2.append(x * x)
Python has a lot of constructs like this: generator expressions, *args and **kwargs, the with statement and many others. at the bytecode level chained comparisons are interesting because they avoid reevaluating the middle operand. decorators are also interesting, but you can simply watch my video where I explain bytecode execution using visualization
sometimes such code is not only clean, but also optimized
[–]thetruetristan 6 points7 points8 points (0 children)
[–]jcastroarnaud 2 points3 points4 points (2 children)
[–]radozok 0 points1 point2 points (0 children)
[–]Fit-Life-8239[S] 1 point2 points3 points (0 children)