{"id":1614,"date":"2024-01-22T23:02:08","date_gmt":"2024-01-22T17:32:08","guid":{"rendered":"https:\/\/geekpython.in\/?p=1614"},"modified":"2024-03-01T17:03:25","modified_gmt":"2024-03-01T11:33:25","slug":"map-function-in-python","status":"publish","type":"post","link":"https:\/\/geekpython.in\/map-function-in-python","title":{"rendered":"How to Use map() Function in Python With Examples"},"content":{"rendered":"\n<p>What would you do if you wanted to apply a function to each item in an iterable? Your first step would be to use that function by iterating over each item with the <code>for<\/code> loop.<\/p>\n\n\n\n<p>Python has a function called <code>map()<\/code> that can help you reduce performing iteration stuff and avoid writing extra code.<\/p>\n\n\n\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\"><div class=\"wp-block-embed__wrapper\">\n<p class=\"responsive-video-wrap clr\"><iframe loading=\"lazy\" title=\"How to use map() function in Python | 2MinutesPy\" width=\"1200\" height=\"675\" src=\"https:\/\/www.youtube.com\/embed\/eCIKq3AIWbU?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" allowfullscreen><\/iframe><\/p>\n<\/div><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Python&#8217;s map() Function<\/h2>\n\n\n\n<p>The <code>map()<\/code> function in Python is a built-in function that allows you to apply a specific function to each item in an iterable without using a <code>for<\/code> loop.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Syntax<\/h3>\n\n\n\n<p><code>map(function, iterable)<\/code><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>function<\/code>: <code>map()<\/code> applies this function to each item in the iterable.<\/li>\n\n\n\n<li><code>iterable<\/code>: list, tuple, string, or iterator object.<\/li>\n<\/ul>\n\n\n\n<p>The <code>map()<\/code> function returns an iterator object containing the result, which can be iterated over to generate values on the fly.<\/p>\n\n\n\n<p>Let&#8217;s take a closer look at the <code>map()<\/code> function with an example.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<p>Consider the following example: a function called <code>add_two()<\/code> adds 2 to the argument <code>a<\/code>. The <code>map()<\/code> function applies the function (<code>add_two()<\/code>) to the iterable stored in the variable <code>my_iterable<\/code>.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \"># Function to be applied\ndef add_two(a):\n    return a + 2\n\n# List of integers\nmy_iterable = [34, 23, 45, 10]\n# Using map() function\nmapping = map(add_two, my_iterable)\nresult = list(mapping)\nprint(f\"Final result: {result}.\")<\/pre><\/div>\n\n\n\n<p>When you run the above code, you&#8217;ll get a list in which each element from the original list <code>my_iterable<\/code> has been incremented by 2, as specified by the <code>add_two<\/code> function.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Final result: [36, 25, 47, 12].<\/pre><\/div>\n\n\n\n<p>You may be wondering how the function is applied to each item in the iterable without the use of an explicit <code>for<\/code> loop. <strong>How does the<\/strong> <code>map()<\/code> <strong>function do it?<\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How map() Function Works?<\/h2>\n\n\n\n<p>You now know that the <code>map()<\/code> function applies a function to each item in the iterable, but how exactly does it do so?<\/p>\n\n\n\n<p>Let me explain with an example. How would you apply a function to the items in a list without using the <code>map()<\/code> function? You&#8217;ll use the <code>for<\/code> loop to iterate through each item in the list and then apply the function.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \"># Function to be applied\ndef add_two(a):\n    return a + 2\n\n# Empty list to store the final result\nfinal_list = []\n\n# List of integers\nmy_iterable = [34, 23, 45, 10]\n# Using for loop\nfor item in my_iterable:\n    result = add_two(item)\n    final_list.append(result)\n\nprint(f\"Final result: {final_list}.\")<\/pre><\/div>\n\n\n\n<p>As you can see in the above code, a <code>for<\/code> loop is used to iterate through each item in the <code>my_iterable<\/code> variable, and within the <code>for<\/code> loop, the <code>add_two<\/code> function is applied to each item, with the result appended to a list <code>final_list<\/code> and printed.<\/p>\n\n\n\n<p>When you run the above code, you will get a similar result as in the first example.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Final result: [36, 25, 47, 12].<\/pre><\/div>\n\n\n\n<p>That is exactly how the <code>map()<\/code> function would have worked in the background for simple operations like the one above.<\/p>\n\n\n\n<p>You can imitate the <code>map()<\/code> function in just one line of code for the above example.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python mark:8 decode:true \"># Function to be applied\ndef add_two(a):\n    return a + 2\n\n# List of integers\nmy_iterable = [34, 23, 45, 10]\n# Using list comprehension\nmapping = [add_two(item) for item in my_iterable]\nprint(f\"Final result: {mapping}.\")<\/pre><\/div>\n\n\n\n<p>Using the list comprehension in the above code eliminated the need to write the additional lines of code.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Processing Multiple Inputs Using map()<\/h2>\n\n\n\n<p>Consider the following scenario: you need to take multiple user inputs and process them using a function. How would you efficiently process the inputs? You can use the <code>map()<\/code> function to accomplish your goal.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python mark:7 decode:true \"># Function to convert Fahrenheit to Celcius\ndef to_celcius(a):\n    val = (a - 32) * 5\/9\n    return round(val)\n\n# Converting each input item into integer\nf_values = list(map(int, input(\"Enter Temperature(in F): \").split()))\n\n# Applying to_celcius function to each item in the iterable\nresult = list(map(to_celcius, f_values))\n\n# Displaying the result\nprint(\"Result:\", result)<\/pre><\/div>\n\n\n\n<p>The code above accepts multiple user inputs, separated by a space (<code>input().split()<\/code>), and the <code>int<\/code> function will be applied to each input using <code>map()<\/code> before being converted into a list using the <code>list<\/code> function.<\/p>\n\n\n\n<p>The next block applies the <code>to_celcius<\/code> function to the iterable <code>f_values<\/code> and prints the results.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Enter Temperature(in F): 1 100 32 273\nResult: [-17, 38, 0, 134]<\/pre><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Using map() with Multiple Iterables<\/h2>\n\n\n\n<p>So far, you&#8217;ve only used the <code>map()<\/code> function with a single iterable, but the <code>map()<\/code> function can accept multiple iterables.<\/p>\n\n\n\n<p>Consider the following example, in which multiple iterables are processed using the <code>map()<\/code> function.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python mark:9 decode:true \">def add(x, y):\n    return x+y\n\n# Iterables\nfirst = [2, 4, 6, 8]\nsecond = [1, 3, 5, 7]\n\n# Both iterables are passed to map()\nmapping = list(map(add, first, second))\nprint(f\"Result: {mapping}.\")<\/pre><\/div>\n\n\n\n<p>In the above code, both iterables (<code>first<\/code> and <code>second<\/code>) and the <code>add<\/code> function is passed to the <code>map()<\/code> function.<\/p>\n\n\n\n<p>The <code>map()<\/code> function iterates each element from both iterable and applies the <code>add<\/code> function. The <code>add()<\/code> function takes two arguments, <code>x<\/code> and <code>y<\/code>, and returns the sum of their values. In the first iteration, <code>x<\/code> will be 2 and <code>y<\/code> will be 1 and the output will be 3 and this will continue till the end of the shortest iterable.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Result: [3, 7, 11, 15].<\/pre><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Using map() with lambda Function<\/h2>\n\n\n\n<p>The <code>lambda<\/code> expression creates an anonymous function in a single line of code. Using the <code>map()<\/code> function and a <code>lambda<\/code> expression, you can achieve the desired result in a few lines of code.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">first = [2, 4, 6, 8]\nsecond = [1, 3, 5, 7]\n\n# Using lambda expression with map()\nmapping = list(map(lambda x, y: x+y, first, second))\nprint(f\"Result: {mapping}.\")<\/pre><\/div>\n\n\n\n<p>The <code>lambda<\/code> expression in the code above is the same as the previous section&#8217;s <code>add<\/code> function. Using the <code>lambda<\/code> expression eliminates the need to explicitly declare a named function, saving a few lines of code.<\/p>\n\n\n\n<p>The above code will produce the following output.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Result: [3, 7, 11, 15].<\/pre><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Manipulating Iterables of String<\/h2>\n\n\n\n<p>Not just integers or floats, the <code>map()<\/code> function can be used to transform iterables containing various types of elements, including strings.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">words = [\"welcome\", \"to\", \"geekpython\"]\n\n# Converting string to uppercase\nuppercase = list(map(str.upper, words))\nprint(f\"Result: {uppercase}.\")\n\n# Capitalizing string\ncapitalize = list(map(str.capitalize, words))\nprint(f\"Result: {capitalize}.\")<\/pre><\/div>\n\n\n\n<p>The <code>map()<\/code> function is used in the above code to apply the <code>str.upper<\/code> and <code>str.capitalize<\/code> functions to the <code>words<\/code> variable (a list of strings). When you run it, you will notice that the strings are transformed.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Result: ['WELCOME', 'TO', 'GEEKPYTHON'].\nResult: ['Welcome', 'To', 'Geekpython'].<\/pre><\/div>\n\n\n\n<p>You can also perform various other operations by declaring a function. For instance, you can declare a function to reverse the strings or slice out some parts from the string.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">words = [\"welcome\", \"to\", \"geekpython\"]\n\n# Reverses a string\ndef reverse(string):\n    return string[: : -1]\n\nrev = list(map(reverse, words))\nprint(f\"Reversed: {rev}.\")\n\n# Slices a string\ndef custom_slice(string):\n    return string[1: 3: 1]\n\nslice_string = list(map(custom_slice, words))\nprint(f\"Sliced:   {slice_string}.\")<\/pre><\/div>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Reversed: ['emoclew', 'ot', 'nohtypkeeg'].\nSliced:   ['el', 'o', 'ee'].<\/pre><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>In simple terms, the <code>map()<\/code> function maps a function to each item in an iterable and returns an iterator object. This iterator can be looped over or converted into a data type, such as a list.<\/p>\n\n\n\n<p>In this article, you&#8217;ve learned:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>What is the <code>map()<\/code> function and how to use it?<\/li>\n\n\n\n<li>How <code>map()<\/code> works and imitating the <code>map()<\/code> function using <code>for<\/code> loop and list comprehension.<\/li>\n\n\n\n<li>Processing multiple user inputs using <code>map()<\/code>.<\/li>\n\n\n\n<li>Processing multiple iterable using <code>map()<\/code>.<\/li>\n\n\n\n<li>Using <code>lambda<\/code> expression with <code>map()<\/code> to eliminate creating a named function.<\/li>\n\n\n\n<li>Manipulating iterable containing string items.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\ud83c\udfc6<strong>Other articles you might be interested in if you liked this one<\/strong><\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/pickle-module-in-python\">Serialize and deserialize Python objects using the pickle module<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/understanding-pytest-to-test-python-code\">How to use pytest to test your Python code<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/build-websocket-server-and-client-using-python\">Create a WebSocket server and client in Python<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/threading-module-to-create-threads-in-python\">Create multi-threaded Python programs using a threading module<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/create-and-integrate-mysql-database-with-flask-app\">Create and integrate MySQL database with Flask app using Python<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/render-images-from-flask\">Upload and display images on the frontend using Flask<\/a>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><strong>That&#8217;s all for now<\/strong><\/p>\n\n\n\n<p><strong>Keep Coding\u270c\u270c<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>What would you do if you wanted to apply a function to each item in an iterable? Your first step would be to use that function by iterating over each item with the for loop. Python has a function called map() that can help you reduce performing iteration stuff and avoid writing extra code. Python&#8217;s [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":1616,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ocean_post_layout":"","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"","ocean_second_sidebar":"","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"","ocean_custom_header_template":"","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"","ocean_menu_typo_font_family":"","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"","ocean_post_oembed":"","ocean_post_self_hosted_media":"","ocean_post_video_embed":"","ocean_link_format":"","ocean_link_format_target":"self","ocean_quote_format":"","ocean_quote_format_link":"post","ocean_gallery_link_images":"on","ocean_gallery_id":[],"footnotes":""},"categories":[41,2],"tags":[31],"class_list":["post-1614","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-function","category-python","tag-python3","entry","has-media"],"_links":{"self":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1614","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/comments?post=1614"}],"version-history":[{"count":4,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1614\/revisions"}],"predecessor-version":[{"id":1624,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1614\/revisions\/1624"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media\/1616"}],"wp:attachment":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media?parent=1614"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/categories?post=1614"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/tags?post=1614"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}