Published in

Coder Life

# Let’s see how it works by code

`def add_ten(nums):    result = []    for i in nums:        result.append(i+10)    return result`
`num_after_add_ten = add_ten([1,20,31,42])print(num_after_add_ten)>>>>>>>>>>>>>>>>>>>>>[11,30,41,52]`
`def add_ten(nums):    for i in nums:        yield (i+10)`
`num_after_add_ten = add_ten([1,20,31,42])print(num_after_add_ten)print next(num_after_add_ten)print next(num_after_add_ten)print next(num_after_add_ten)print next(num_after_add_ten)print next(num_after_add_ten)>>>>>>>>>>>>>>>>>>>>><generator object add_ten at xxxxxx>11304152StopIteration`
`num_after_add_ten = add_ten([1,20,31,42])for num in num_after_add_ten:    print num>>>>>>>>>>>>>>>>>>>>>>>11304152`
`#Originalnum_after_add_ten = [x+10 for x in [1,20,31,42]]#Change into Operator typenum_after_add_ten = (x+10 for x in [1,20,31,42])for x in num_after_add_ten:    print x>>>>>>>>>>>>>>>11304152`
`num_after_add_ten = (x+10 for x in [1,20,31,42])print list(num_after_add_ten)>>>>>>[11, 30, 41, 52]`

# Pros and Cons

## Pros

• Generators yield one value at a time from a set of items, not holding all data makes it requires less space of the memory.
• It also took much less time than a list comprehensions when operating
• It is more readable when comparing with using `return`.

## Cons

• List comprehensions can be traversed by times while the generator can only be called once.

--

--

## Get the Medium app

A tech enthusiast who is keen to develop new skills | Contact Me: allie.chiayu.hsu@gmail.com