Python: Map Function to List

By Xah Lee. Date: . Last updated: .

Map Function to List

map(f, list) → applies function f to all elements in list. Return a iterator of the result. (does not modify the original list)

Note: python 2, map, filter, return a list. In python 3, they return a iterator object that represent the list.

list(iterator_obj) → return a list represented by iterator_obj.

# python 3

def ff(nn):
    return nn+1

bb = map(ff, [1,2,3,4])
print(bb)
# <map object at 0x10ad77cf8>

print( list(bb) )
# [2, 3, 4, 5]

map(f, li1, li2, li3, ) → applies f to all lists in parallel. That is, first element of result would be f(e1,e2,e3) where its args are first elemet of each list. f should take same number args as there are lists. All lists must have same number of elements (if short, None is used). Return the new iterator.

# python 3

def ff(x1, x2, x3):
    return str(x1)+ str(x2) + str(x3)

print( list(map(ff, [1, 2, 3], ["a", "b", "c"], [4, 5, 6])) )
# ['1a4', '2b5', '3c6']

Filter List

filter(f, list) → return a new iterator, such that f(element) returns True.

# python 3

# return True if divisible by 2
def ff(n): return n % 2 == 0

aa = range(11)

bb = filter( ff, aa)

print(list(bb))
# [0, 2, 4, 6, 8, 10]

Python List, Tuple, Dictionary

  1. List Basics
  2. Loop Thru List
  3. Map f to List
  4. Copy Nested List
  5. List Comprehension
  6. List Methods
  7. Sort
  8. Dictionary
  9. Loop Thru Dict
  10. Dict Methods
  11. Tuple
  12. Sets, Union, Intersection

If you have a question, put $5 at patreon and message me.

Python

  1. Python 3 Basics
  2. Python 2 Basics
  3. Python 2 and 3 Difference
  4. Print Version
  5. Builtin Help
  6. Quote String
  7. String Methods
  8. Format String
  9. Operators
  10. Complex Numbers
  11. True, False
  12. if then else
  13. Loop
  14. List Basics
  15. Loop Thru List
  16. Map f to List
  17. Copy Nested List
  18. List Comprehension
  19. List Methods
  20. Sort
  21. Dictionary
  22. Loop Thru Dict
  23. Dict Methods
  24. Tuple
  25. Sets
  26. Function
  27. Closure
  28. 2 Closure
  29. Decorator
  30. Class
  31. Object, ID, Type
  32. List Modules
  33. Write a Module
  34. Unicode 🐍

Regex

  1. Regex Basics
  2. Regex Reference

Text Processing

  1. Read/Write File
  2. Traverse Directory
  3. File Path
  4. Process Unicode
  5. Convert File Encoding
  6. Find Replace in dir
  7. Find Replace by Regex
  8. Count Word Frequency

Web

  1. Send Email
  2. GET Web Page
  3. Web Crawler
  4. HTTP POST

Misc

  1. JSON
  2. Find Script Path
  3. Get Env Var
  4. System Call
  5. Decompress Gzip
  6. Append String in Loop
  7. Timing f timeit
  8. Keyword Arg Default Value Unstable
  9. Check Page Load Size
  10. Thumbnail Generation