{"id":74725,"date":"2020-01-04T10:22:15","date_gmt":"2020-01-04T04:52:15","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=74725"},"modified":"2020-01-04T10:22:15","modified_gmt":"2020-01-04T04:52:15","slug":"python-list-comprehension","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/python-list-comprehension\/","title":{"rendered":"Python List Comprehension &#8211; Time to upskill your programming"},"content":{"rendered":"<p>In today\u2019s article, we are going to discuss a very important topic, that is, Python list comprehension. It is a very <strong>powerful<\/strong> way to perform <strong>complex operations<\/strong> and <strong>manipulate<\/strong> <strong>iterables<\/strong>.<\/p>\n<p>First, we will take a quick look at lists and then move towards the list comprehension. We will see various ways of how you can use <strong>list comprehension<\/strong> and become a <strong>better programmer<\/strong>.<\/p>\n<h3>What are Lists?<\/h3>\n<p>Lists are a <strong>mutable collection<\/strong> of <strong>elements<\/strong>. They can be of any type like <strong>strings<\/strong>, <strong>numbers<\/strong>, <strong>sets<\/strong>, <strong>booleans<\/strong>, etc. They are created by using <strong>square brackets<\/strong>.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">List = [1, 2, 3, \u201dAB\u201d, \u201cDC\u201d]<\/pre>\n<p>We can access them with <strong>indexes<\/strong> starting from <strong>zero<\/strong>. It also supports <strong>slicing<\/strong>.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">print(List[1])\nprint(List[1:3])<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">2<br \/>\n[2, 3]<\/div>\n<h3>Python List comprehension<\/h3>\n<p>List comprehensions are an <strong>easy<\/strong>, <strong>concise<\/strong>, and <strong>fast <\/strong>way to <strong>build lists<\/strong>. It allows you to perform <strong>complex operations<\/strong> on lists easily using a <strong>single line<\/strong>.<\/p>\n<p>First, observe this code.<\/p>\n<p>Suppose you want to iterate over a <strong>list<\/strong>, <strong>check a condition<\/strong> and then <strong>manipulate<\/strong> it with <strong>expression<\/strong> and <strong>append<\/strong> the <strong>result<\/strong> in a new list.<\/p>\n<p>The code will look something like this.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">new_list = []\nfor i in old_list:\n    if filter(i):\n        new_list.append(expressions(i))<\/pre>\n<p>But with Python list comprehension, we can do this in <strong>one line<\/strong>.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">new_list = [ expressions(i) for i in old_list if filter(i) ]<\/pre>\n<p>Once you understand this, it will be a lot easier to code this way.<\/p>\n<p><strong>Syntax:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">[ expression for item in list if conditional ]<\/pre>\n<h3>How you can Use Python List Comprehension<\/h3>\n<h4>1. Simple List Comprehension<\/h4>\n<p>Simple use of a Python list comprehension is when you want to <strong>iterate<\/strong> over a <strong>list<\/strong> and perform a <strong>quick operation<\/strong> on the elements.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">nums = [1,2,3,4,5]\n\nnew_nums = [ i+10 for i in nums]\npower_nums = [i**2 for i in nums]\n\nprint(new_nums)\nprint(power_nums)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">[11, 12, 13, 14, 15]<br \/>\n[1, 4, 9, 16, 25]<\/div>\n<h4>2. List Comprehension with Conditions<\/h4>\n<p>List comprehensions also provide a way to check for <strong>conditions<\/strong> and <strong>filter<\/strong> out the elements you don\u2019t need from the list.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">nums = [1, 12, 8, 14, 9, 23, 36, 5, 4 ]\n\ngreater_ten = [i for i in nums if(i&gt;10)]\nevens = [i for i in nums if(i%2==0)]\n\nprint(\u201cGreater than ten :\u201d,greater_ten)\nprint(\u201cEven numbers list :\u201d,evens)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Greater than ten : [12, 14, 23, 36]<br \/>\nEven numbers list : [12, 8, 14, 36, 4]<\/div>\n<h4>3. List Comprehension with Nested Conditions<\/h4>\n<p>Till now, in Python list comprehension, we have seen <strong>simple conditions<\/strong> but what about some <strong>nested conditions<\/strong>?<\/p>\n<p>Let\u2019s see how we can use nested conditions in a list comprehension.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">print([i for i in range(100) if(i%2==0) if(i%5==0) ])<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]<\/div>\n<p>Here, we used two conditions <strong>separated by space<\/strong>.<\/p>\n<p>It works by first checking the <strong>first condition<\/strong> and <strong>filters out<\/strong> the numbers that are <strong>divisible<\/strong> by <strong>2<\/strong> and then from those numbers, it will <strong>filter out<\/strong> the numbers divisible by <strong>5<\/strong>.<\/p>\n<h4>4. If-else Condition in List Comprehension<\/h4>\n<p>Let us see how we can use the<strong> if-else statements<\/strong> in a Python list comprehension. If-else conditions are very <strong>useful<\/strong> and <strong>widely used<\/strong>, using them in list comprehensions will make it even more <strong>powerful<\/strong>.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">print([ x+1 if(x%2==0) else x**2 for x in [1,2,3,4,5,6,7,8] ])<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">[1, 3, 9, 5, 25, 7, 49, 9]<\/div>\n<p>Here, we use the if-else statement in the <strong>first position<\/strong> and we <strong>incremented<\/strong> <strong>one<\/strong> to <strong>even numbers<\/strong> and <strong>squared<\/strong> the <strong>odd numbers<\/strong>.<\/p>\n<p>List comprehensions make this an easy task.<\/p>\n<h4>5. Nested List Comprehension<\/h4>\n<p>Suppose you have a list like this:<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">List = [[1,2,3], [4,5,6], [3,4] ]<\/pre>\n<p>Now to iterate over each element, we will have to <strong>nest<\/strong> <strong>inside<\/strong> the list comprehension.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">[ res for x in List for res in x]<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">[1, 2, 3, 4, 5, 6, 3, 4]<\/div>\n<p>For understanding purposes, you can think of this statement as:<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">for x in List:\n  for res in x:\n    print(res)<\/pre>\n<p>This way we can <strong>flatten<\/strong> a <strong>nested list<\/strong>.<\/p>\n<p>So far, we were discussing <strong>list comprehensions<\/strong> in Python but now we can see similar comprehension techniques in the <strong>dictionary<\/strong>, <strong>sets<\/strong>, and <strong>generators<\/strong>.<\/p>\n<h3>Python Dictionary Comprehension<\/h3>\n<p>Python allows us to create <strong>dictionary comprehensions<\/strong>. The syntax is <strong>similar<\/strong> to list comprehensions in <strong>Python<\/strong>.<\/p>\n<p><strong>Syntax:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">{key: expression(i) for (key, i) in iterable}<\/pre>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">num=[1,2,3,4]\nname=['one','two','three','four']\n\nmy_dict = {num:name for (num,name) in zip(num,name)}\nprint(my_dict)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">{1: &#8216;one&#8217;, 2: &#8216;two&#8217;, 3: &#8216;three&#8217;, 4: &#8216;four&#8217;}<\/div>\n<p>You can also use list comprehensions to <strong>create<\/strong> dictionary comprehensions.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">even_squares = {x: x**2 for x in range(0,12,2)}\nprint(even_squares)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">{0: 0, 2: 4, 4: 16, 6: 36, 8: 64, 10: 100}<\/div>\n<h3>Python Sets Comprehension<\/h3>\n<p>Lets us now see how sets comprehensions work.<\/p>\n<p><strong>Syntax:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">{ expression(i) for i in iterable condition }<\/pre>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">odd = { num for num in [1,2,3,4,5,6] if num%2==1}\nprint(odd)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">{1, 3, 5}<\/div>\n<h3>Python Generator Comprehensions<\/h3>\n<p>A quick way to create generators is with <strong>generator comprehensions<\/strong>.<\/p>\n<p><strong>Syntax:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">(expression(i) for i in iterable)<\/pre>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">gen = (x**2 for x in range(100))\nprint(gen)\nnext(gen)\nnext(gen)\nnext(gen)\nnext(gen)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">&lt;generator object &lt;genexpr&gt; at 0x000001EA897B0BA0&gt;<br \/>\n0<br \/>\n1<br \/>\n4<br \/>\n9<\/div>\n<h3>Summary<\/h3>\n<p>This was all about the <strong>Python list comprehensions<\/strong>. Now you can clean up your code by writing <strong>simple<\/strong> and <strong>concise code<\/strong>. You can easily <strong>modify<\/strong> lists using list comprehensions.<\/p>\n<p>You should use list comprehensions in Python more often whenever possible but make sure not to write <strong>lengthy<\/strong> list comprehensions, then it would be better to use for <strong>loops<\/strong>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In today\u2019s article, we are going to discuss a very important topic, that is, Python list comprehension. It is a very powerful way to perform complex operations and manipulate iterables. First, we will take&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":74802,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1053],"tags":[1177,1178,1179,1180,1181],"class_list":["post-74725","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-list-comprehension-in-python","tag-python-dictionary-comprehension","tag-python-generator-comprehension","tag-python-list-comprehension","tag-python-list-comprehension-usage"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Python List Comprehension - Time to upskill your programming - TechVidvan<\/title>\n<meta name=\"description\" content=\"Python List Comprehension - Explore lists &amp; list comprehension in Python &amp; how to use it. Also, get to know about dictionary, set &amp; generator comprehension.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/python-list-comprehension\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python List Comprehension - Time to upskill your programming - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Python List Comprehension - Explore lists &amp; list comprehension in Python &amp; how to use it. Also, get to know about dictionary, set &amp; generator comprehension.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/python-list-comprehension\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2020-01-04T04:52:15+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2019\/12\/Python-list-comprehension.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"802\" \/>\n\t<meta property=\"og:image:height\" content=\"420\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python List Comprehension - Time to upskill your programming - TechVidvan","description":"Python List Comprehension - Explore lists & list comprehension in Python & how to use it. Also, get to know about dictionary, set & generator comprehension.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/python-list-comprehension\/","og_locale":"en_US","og_type":"article","og_title":"Python List Comprehension - Time to upskill your programming - TechVidvan","og_description":"Python List Comprehension - Explore lists & list comprehension in Python & how to use it. Also, get to know about dictionary, set & generator comprehension.","og_url":"https:\/\/techvidvan.com\/tutorials\/python-list-comprehension\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2020-01-04T04:52:15+00:00","og_image":[{"width":802,"height":420,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2019\/12\/Python-list-comprehension.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/python-list-comprehension\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-list-comprehension\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Python List Comprehension &#8211; Time to upskill your programming","datePublished":"2020-01-04T04:52:15+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-list-comprehension\/"},"wordCount":636,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-list-comprehension\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2019\/12\/Python-list-comprehension.jpg","keywords":["list comprehension in python","Python Dictionary Comprehension","python generator comprehension","python list comprehension","python list comprehension usage"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/python-list-comprehension\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/python-list-comprehension\/","url":"https:\/\/techvidvan.com\/tutorials\/python-list-comprehension\/","name":"Python List Comprehension - Time to upskill your programming - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-list-comprehension\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-list-comprehension\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2019\/12\/Python-list-comprehension.jpg","datePublished":"2020-01-04T04:52:15+00:00","description":"Python List Comprehension - Explore lists & list comprehension in Python & how to use it. Also, get to know about dictionary, set & generator comprehension.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-list-comprehension\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/python-list-comprehension\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/python-list-comprehension\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2019\/12\/Python-list-comprehension.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2019\/12\/Python-list-comprehension.jpg","width":802,"height":420,"caption":"Python list comprehension"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/python-list-comprehension\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Python List Comprehension &#8211; Time to upskill your programming"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/74725","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=74725"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/74725\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/74802"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=74725"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=74725"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=74725"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}