Python For Loop - Switching from PHP -
i new python , use php. can please clear me structure of loop python.
numbers = int(x) x in numbers
in php realted loop used inside body. can't understand why methods before loop in python.
first of statement missing brackets:
numbers = [int(x) x in numbers]
this called list comprehension , equivalent of:
numbers = [] x in numbers: numbers.append(int(x))
note can use comprehensions generator expressions, in case [] become ():
numbers = (int(x) x in numbers)
which equivalent of:
def numbers(n): x in n: yield int(x)
this means loop execute 1 yield
@ time being processed. in other words, while first example builds list in memory, generator returns 1 element @ time when executed. great process large lists can generate 1 element time without getting memory (e.g. processing file line-by-line).
so can see comprehensions , generator expressions great way reduce amount of code required process lists, tuples , other iterable.
Comments
Post a Comment