Map in Python :
Note: For more information refer to Python map() function.
for loop in Python :
- We use for loop to repeat a block of code for fixed number of times .
- Used when no results are required .
- To perform sequential traversal .
- Loop from 0 to n runs n+1 times .
-
for var in iterable :
statements
Note: Here, var is the name given to iterating variable, iterable can be replaced by range() function and they can be of any data type . Statements are the step of actions to be performed .
Note: For more information, refer to Python For Loops.
Example:
Python
def squareNum (a) :
return a * a
listt = [0, -1, 3, 4.5, 99, .08]
x = map(squareNum, listt)
print(x)
print(list(x))
for i in listt :
square = i * i
print(square)
|
Output:
<map object at 0x7fe413cf9b00>
[0, 1, 9, 20.25, 9801, 0.0064]
0
1
9
20.25
9801
0.0064
Map vs for loop
- Comparing performance , map() wins! map() works way faster than for loop. Considering the same code above when run in this ide.
Using map():

using for loop:

- for loop can be with no content, no such concept exist in map() function.
Example:
Python
for i in range (10) :
pass
|
- There can be an
else condition in for loop which only runs when no break statement is used. There is nothing like this in map.
Example :
Python
for i in range(10) :
print(i)
else :
print("Finished !")
|
Output :
0
1
2
3
4
5
6
7
8
9
Finished !
- for loop can exit before too. We can do that using
break statement. Exiting before expected is not possible in map.
- map generates a map object, for loop does not return anything.
- syntax of map and for loop are completely different.
- for loop is for executing the same block of code for a fixed number of times, the map also does that but in a single line of code.
Let us see the differences in a tabular form -:
| |
Map() |
forloop |
| 1. |
The map() function executes a specified function for each item in an iterable. |
The for loop is used for iterating over a sequence. |
| 2. |
Its syntax is -:
map(function, iterables)
|
It is used by using for keyword. |
| 3. |
In this, the item is sent to the function as a parameter. |
It is used to execute a set of statements, once for each item in a list, tuple, set etc. |
| 4. |
It takes two parameters function and iterables. |
Its syntax is -:
for var in iterable : statements
|
Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills, become a part of the hottest trend in the 21st century.Dive into the future of technology - explore the
Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
03 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...