Python Various Ways of Writing Loops

Python Various Ways of Writing Loops

  1. List Comprehension
[2*x+3 for x in list]
  1. map
map(function, list)

A function can also be defined on the fly.

map(lambda x: function of x, list)

For multivariable,

map(lambda x,y:x+y, xlist, ylist)
  1. zip and map

zip is useful in a map of multivariable function.

map(functionofxy, zip(xlist,ylist))

As given in the reference link, one good example is

map(sum,zip(A,B,C))
  1. map and list comprehension
[map(lambda x: x+3, list) for list in shape2by2list]

Ref. Great Python Tricks for avoiding unnecessary loops in your code

Planted: by ;

L Ma (2015). 'Python Various Ways of Writing Loops', Datumorphism, 12 April. Available at: https://datumorphism.leima.is/til/programming/python/python-writing-loops/.