{"id":98,"date":"2017-01-13T15:43:07","date_gmt":"2017-01-13T15:43:07","guid":{"rendered":"https:\/\/159.69.80.24\/blog\/list-comprehensions-and-generator-expressions\/"},"modified":"2024-10-28T14:59:07","modified_gmt":"2024-10-28T14:59:07","slug":"list-comprehensions-and-generator-expressions","status":"publish","type":"post","link":"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/","title":{"rendered":"List Comprehensions in Python and Generator Expressions"},"content":{"rendered":"<p>Do you know the difference between the following syntax?<\/p>\n<p><strong>[x for x in range(5)]<\/strong><br \/>\n<strong>(x for x in range(5))<\/strong><br \/>\n<strong>tuple(range(5))<\/strong><\/p>\n<p>This is exactly what differentiates Python from other languages and makes <a href=\"https:\/\/djangostars.com\/blog\/python-best-programming-language-for-startup\/\">Python the best programming language<\/a>. Coming from functional languages and being implemented in Python from early days, list comprehension became its distinctive feature.<\/p>\n<p>This article is a complete guide to list comprehensions and generator expressions in Python. It provides many practical examples of their usage.<\/p>\n<p>You\u2019ll know:<\/p>\n<ul>\n<li>What list comprehensions and generator expressions look like in Python.<\/li>\n<li>How to create them correctly.<\/li>\n<li>Where they are best to use.<\/li>\n<li>Differences Between Iterable and Iterator.<\/li>\n<li>Benefits of using list comprehensions and generator expressions in Python.<\/li>\n<\/ul>\n<p>Let\u2019s dive deeper into the Python list comprehensions and generator expressions. In Django Stars, a <a href=\"https:\/\/djangostars.com\/services\/python-development\/\">Python development company<\/a>, we often use list comprehensions in <a href=\"https:\/\/djangostars.com\/case-studies\/\">our projects<\/a>, so if you need additional advice on Python or <a href=\"https:\/\/djangostars.com\/services\/python-django-development\/\">Django development<\/a>, you just need to <a href=\"https:\/\/djangostars.com\/get-in-touch\/\">contact us<\/a>.<\/p>\n<p>Read Also: <a href=\"https:\/\/djangostars.com\/blog\/debugging-python-applications-with-pdb\/\">Debugging Python Applications with the PDB Module<\/a><\/p>\n<h2>4 Facts About the Lists<\/h2>\n<p>First off, a short review on the lists (arrays in other languages).<\/p>\n<ul>\n<li>List is a type of data that can be represented as a collection of elements. Simple list looks like this &#8211; [0, 1, 2, 3, 4, 5]<\/li>\n<li>Lists take all possible types of data and combinations of data as their components:<\/li>\n<\/ul>\n<pre><code class=\"language-language python\">&gt;&gt;&gt; a = 12\r\n&gt;&gt;&gt; b = \"this is text\"\r\n&gt;&gt;&gt; my_list = [0, b, ['element', 'another element'], (1, 2, 3), a]\r\n&gt;&gt;&gt; print(my_list)\r\n[0, 'this is text', ['element', 'another element'], (1, 2, 3), 12]\r\n<\/code><\/pre>\n<ul>\n<li>Lists can be indexed. You can get access to any individual element or group of elements using the following syntax:<\/li>\n<\/ul>\n<pre><code class=\"language-language python\">&gt;&gt;&gt; a = ['red', 'green', 'blue']\r\n&gt;&gt;&gt; print(a[0])\r\nred\r\n<\/code><\/pre>\n<ul>\n<li>Lists are mutable in Python. This means you can replace, add or remove elements.<\/li>\n<\/ul>\n<h3>How to Create a List in Python<\/h3>\n<p>There are 2 common ways how to create lists in Python:<\/p>\n<pre><code class=\"language-language python\">&gt;&gt;&gt; my_list = [0, 1, 1, 2, 3]<\/code><\/pre>\n<p>And less preferable:<\/p>\n<pre><code class=\"language-language python\">&gt;&gt;&gt; my_list = list()<\/code><\/pre>\n<p>Usually, <b>list(obj)<\/b> is used to transform another sequence into the list. For example we want to split string into separate symbols:<\/p>\n<pre><code class=\"language-language python\">&gt;&gt;&gt; string = \"string\"\r\n&gt;&gt;&gt; list(string)\r\n['s', 't', 'r', 'i', 'n', 'g']<\/code><\/pre>\n<h2>What is List Comprehension?<\/h2>\n<p>Often seen as a part of functional programming in Python, list comprehension allows you to create lists with less code. List comprehensions enhance <a href=\"https:\/\/djangostars.com\/blog\/python-performance-improvement\/\">Python code performance<\/a> by being faster and more efficient than traditional <code>for<\/code> loops. They also improve code readability and conciseness, making it easier to write and maintain. In short, it\u2019s a truly Pythonic way of coding. Less code &#8211; more effectiveness.<\/p>\n<p>Let\u2019s look at the following example.<\/p>\n<p>You create a list using a for loop and a <strong>range()<\/strong> function.<\/p>\n<pre><code class=\"language-language python\">&gt;&gt;&gt; my_list = []\r\n&gt;&gt;&gt; for x in range(10):\r\n... my_list.append(x * 2)\r\n...\r\n&gt;&gt;&gt; print(my_list)\r\n[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]\r\n<\/code><\/pre>\n<p>And this is how the implementation of the previous example is performed using a list comprehension:<\/p>\n<pre><code class=\"language-language python\">&gt;&gt;&gt; comp_list = [x * 2 for x in range(10)]\r\n&gt;&gt;&gt; print(comp_list)\r\n[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]\r\n<\/code><\/pre>\n<p>The above example is oversimplified to get the idea of syntax. The same result may be achieved simply using <strong>list(range(0, 19, 2))<\/strong> function. However, you can use a more complex modifier in the first part of the comprehension or add a condition that will filter the list. Something like this:<\/p>\n<pre><code class=\"language-language python\">&gt;&gt;&gt; comp_list = [x ** 2 for x in range(7) if x % 2 == 0]\r\n&gt;&gt;&gt; print(comp_list)\r\n[4, 16, 36]\r\n<\/code><\/pre>\n<p>Another available option is to use list comprehension to combine several lists and create a list of lists. At first glance, the syntax seems to be complicated. It may help to think of lists as outer and inner sequences.<br \/>\nIt\u2019s time to show the power of list comprehension when you want to create a list of lists by combining two existing lists.<\/p>\n<pre><code class=\"language-language python\">&gt;&gt;&gt; nums = [1, 2, 3, 4, 5]\r\n&gt;&gt;&gt; letters = ['A', 'B', 'C', 'D', 'E']\r\n&gt;&gt;&gt; nums_letters = [[n, l] for n in nums for l in letters]\r\n#the comprehensions list combines two simple lists in a complex list of lists.\r\n&gt;&gt;&gt; print(nums_letters)\r\n&gt;&gt;&gt; print(nums_letters)\r\n[[1, 'A'], [1, 'B'], [1, 'C'], [1, 'D'], [1, 'E'], [2, 'A'], [2, 'B'], [2, 'C'], [2, 'D'], [2, 'E'], [3, 'A'], [3, 'B'], [3, 'C'], [3, 'D'], [3, 'E'], [4, 'A'], [4, 'B'], [4, 'C'], [4, 'D'], [4, 'E'], [5, 'A'], [5, 'B'], [5, 'C'], [5, 'D'], [5, 'E']]\r\n&gt;&gt;&gt;\r\n<\/code><\/pre>\n<p>Let\u2019s try it with text or, referring to it correctly, string object.<\/p>\n<pre><code class=\"language-language python\">&gt;&gt;&gt; iter_string = \"some text\"\r\n&gt;&gt;&gt; comp_list = [x for x in iter_string if x !=\" \"]\r\n&gt;&gt;&gt; print(comp_list)\r\n['s', 'o', 'm', 'e', 't', 'e', 'x', 't']\r\n<\/code><\/pre>\n<p>The comprehensions are not limited to lists. You can create dicts and sets comprehensions as well with the Python set generator.<\/p>\n<pre><code class=\"language-language python\">&gt;&gt;&gt; dict_comp = {x:chr(65+x) for x in range(1, 11)}\r\n&gt;&gt;&gt; type(dict_comp)\r\n&lt;class 'dict'&gt;\r\n&gt;&gt;&gt; print(dict_comp)\r\n{1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F', 6: 'G', 7: 'H', 8: 'I', 9: 'J', 10: 'K'}\r\n<\/code><\/pre>\n<pre><code class=\"language-language python\">&gt;&gt;&gt; set_comp = {x ** 3 for x in range(10) if x % 2 == 0}\r\n&gt;&gt;&gt; type(set_comp)\r\n&lt;class 'set'&gt;\r\n&gt;&gt;&gt; print(set_comp)\r\n{0, 8, 64, 512, 216}\r\n<\/code><\/pre>\n<h2>When to Use List Comprehensions in Python<\/h2>\n<p>List comprehension is the best way to enhance the code readability, so it&#8217;s worth using whenever there is a bunch of data to be checked with the same function or logic \u2013 for example, KYC verification. If the logic is quite simple, for instance, it&#8217;s limited with `true` or `false` results, list comprehension can optimize the code and focus on the logic solely. For example:<\/p>\n<pre><code class=\"language-language python\">&gt;&gt;&gt; customers = [{\"is_kyc_passed\": False}, {\"is_kyc_passed\": True}]\r\n&gt;&gt;&gt; kyc_results = []\r\n&gt;&gt;&gt; for customer in customers:\r\n...     kyc_results.append(customer[\"is_kyc_passed\"])\r\n...\r\n&gt;&gt;&gt; all(kyc_results)\r\nFalse<\/code><\/pre>\n<p>There are many other ways how it can be implemented, but let&#8217;s have a look at the example with list comprehension:<\/p>\n<pre><code class=\"language-language python\">&gt;&gt;&gt; customers = [{\"is_kyc_passed\": False}, {\"is_kyc_passed\": True}]\r\n&gt;&gt;&gt; all(customer[\"is_kyc_passed\"] for customer in customers)\r\nFalse<\/code><\/pre>\n<h2>Benefits of Using List Comprehensions<\/h2>\n<p>List comprehensions optimize the lists\u2019 generation and help to avoid side effects as gibberish variables. As a result, you get more concise and readable code.<br \/>\nFor a better understanding of what benefits list comprehensions brings to <a href=\"https:\/\/djangostars.com\/services\/hire-python-developers\/\">Python developers<\/a>, one can also pay attention to the following:<\/p>\n<ul>\n<li>Ease of code writing and reading. By using list comprehensions for Python list creation, developers can make their code easier to understand and reduce the number of lines, primarily by replacing for loops.<\/li>\n<li>Improved execution speed. List comprehensions not only provide a convenient way to write code but also execute faster. Since <a href=\"https:\/\/djangostars.com\/blog\/django-performance-optimization-tips\/\">performance<\/a> is usually not considered one of the <a href=\"https:\/\/djangostars.com\/blog\/python-web-development\/\">pros of using Python for web development<\/a>, this aspect shouldn\u2019t be neglected when programming and refactoring.<\/li>\n<li>No modification of existing lists. A list comprehension call is a new list creation Python performs without changing the existing one. And this fact allows using of list comprehensions in a functional programming paradigm.<\/li>\n<\/ul>\n<h2>Difference Between Iterable and Iterator<\/h2>\n<p>It will be easier to understand the concept of Python list generators if you get the idea of iterables and iterators.<br \/>\nIterable is a &#8220;sequence&#8221; of data, you can iterate over using a loop. The easiest visible example of iterable can be a list of integers &#8211; [1, 2, 3, 4, 5, 6, 7]. However, it\u2019s possible to iterate over other types of data like strings, dicts, tuples, sets, etc.<br \/>\nBasically, any object that has <b>iter()<\/b> method can be used as an iterable. You can check it using <b>hasattr()<\/b> function in the interpreter.<\/p>\n<pre><code class=\"language-language python\">&gt;&gt;&gt; hasattr(str, '__iter__')\r\nTrue\r\n&gt;&gt;&gt; hasattr(bool, '__iter__')\r\nFalse\r\n<\/code><\/pre>\n<p>Iterator protocol is implemented whenever you iterate over a sequence of data. For example, when you use a for loop the following is happening on a background:<\/p>\n<ul>\n<li>first <strong>iter()<\/strong> method is called on the object to convert it to an iterator object.<\/li>\n<li><strong>next()<\/strong> method is called on the iterator object to get the next element of the sequence.<\/li>\n<li><strong>StopIteration<\/strong> exception is raised when there are no elements left to call.<\/li>\n<\/ul>\n<pre><code class=\"language-language python\">&gt;&gt;&gt; simple_list = [1, 2, 3]\r\n&gt;&gt;&gt; my_iterator = iter(simple_list)\r\n&gt;&gt;&gt; print(my_iterator)\r\n&lt;list_iterator object at 0x7f66b6288630&gt;\r\n&gt;&gt;&gt; next(my_iterator)\r\n1\r\n&gt;&gt;&gt; next(my_iterator)\r\n2\r\n&gt;&gt;&gt; next(my_iterator)\r\n3\r\n&gt;&gt;&gt; next(my_iterator)\r\nTraceback (most recent call last):\r\nFile \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\r\nStopIteration\r\n<\/code><\/pre>\n<h2>Generator Expressions<\/h2>\n<p>In Python, generators provide a convenient way to implement the iterator protocol. Generator is an iterable created using a function with a <b>yield<\/b> statement.<br \/>\nThe main feature of generator expression is evaluating the elements on demand. When you call a normal function with a return statement the function is terminated whenever it encounters a return statement. In a function with a <b>yield<\/b> statement the state of the function is \u201csaved\u201d from the last call and can be picked up the next time you call a generator function.<\/p>\n<pre><code class=\"language-language python\">&gt;&gt;&gt; def my_gen():\r\n... for x in range(5):\r\n... yield x\r\n<\/code><\/pre>\n<p>A Python generator expression is an expression that returns a generator (generator object).<br \/>\nGenerator expression in Python allows creating a generator on a fly without a <b>yield<\/b> keyword. However, it doesn\u2019t share the whole power of generator created with a yield function. The syntax and concept is similar to list comprehensions:<\/p>\n<pre><code class=\"language-language python\">&gt;&gt;&gt; gen_exp = (x ** 2 for x in range(10) if x % 2 == 0)\r\n&gt;&gt;&gt; for x in gen_exp:\r\n... print(x)\r\n4\r\n16\r\n36\r\n64\r\n<\/code><\/pre>\n<p>In terms of syntax, the only difference is that you use parentheses instead of square brackets. However, the types of data returned by Python generator expressions and list comprehensions differ.<\/p>\n<pre><code class=\"language-language python\">&gt;&gt;&gt; list_comp = [x ** 2 for x in range(10) if x % 2 == 0]\r\n&gt;&gt;&gt; gen_exp = (x ** 2 for x in range(10) if x % 2 == 0)\r\n&gt;&gt;&gt; print(list_comp)\r\n[0, 4, 16, 36, 64]\r\n&gt;&gt;&gt; print(gen_exp)\r\n&lt;generator object &lt;genexpr&gt; at 0x7f600131c410&gt;\r\n<\/code><\/pre>\n<p>The main advantage of generator over a list is that it takes much less memory. We can check how much memory is taken by both types using <strong>sys.getsizeof()<\/strong> method.<br \/>\n<b>Note:<\/b> in Python 2 using <strong>range()<\/strong> function can&#8217;t actually reflect the advantage in term of size, as it still keeps the whole list of elements in memory. In Python 3, however, this example is viable as the <strong>range()<\/strong> returns a range object.<\/p>\n<pre><code class=\"language-language python\">&gt;&gt;&gt; from sys import getsizeof\r\n&gt;&gt;&gt; my_comp = [x * 5 for x in range(1000)]\r\n&gt;&gt;&gt; my_gen = (x * 5 for x in range(1000))\r\n&gt;&gt;&gt; getsizeof(my_comp)\r\n9024\r\n&gt;&gt;&gt; getsizeof(my_gen)\r\n88\r\n<\/code><\/pre>\n<p>We can see this difference because while `list` creating Python reserves memory for the whole list and calculates it on the spot. In case of generator, we receive only &#8221;algorithm&#8221;\/ &#8220;instructions&#8221; how to calculate that Python stores. And each time we call for generator, it will only \u201cgenerate\u201d the next element of the sequence on demand according to &#8220;instructions&#8221;.<br \/>\nOn the other hand, generator will be slower, as every time the element of sequence is calculated and yielded, function context\/state has to be saved to be picked up next time for generating next value. That &#8220;saving and loading function context\/state&#8221; takes time.<br \/>\n<b>Note:<\/b> Of course, there are different ways to provide Python &#8216;generator to list&#8217; conversion, besides initial using square brackets where Python generates lists via list comprehension. If it&#8217;s necessary to convert a generator to a list, Python developers can use, for example, the <b>list()<\/b> function or the unpack operator <b>*<\/b>.<\/p>\n<p>Read also: <a href=\"https:\/\/djangostars.com\/blog\/python-rule-engine\/\">Python Rule Engine: Logic Automation &amp; Examples<\/a><br \/>\n<div class=\"info_box_shortcode_holder\" style=\"background-image: url(https:\/\/djangostars.com\/blog\/wp-content\/uploads\/2023\/08\/Web-Development_1.png)\">\n    <div class=\"info_box_label\">\n    Services\n    <\/div>\n    <div class=\"info_box_logo\">\n    \n    <\/div>\n    \n    <div class=\"info_box_title font_size_\">\n   <span class=\"info_box_title_inner\">Boost your web development.&lt;br \/&gt;\n<\/span>\n    <\/div>\n    <div class=\"info_box_link\">\n        <a href=\"https:\/\/djangostars.com\/services\/web-development\/\" target=\"_blank\" >\n            <span>Learn More<\/span>\n            <div class=\"button_animated\">\n                <svg width=\"24\" height=\"12\" viewBox=\"0 0 24 12\" fill=\"none\"\n                     xmlns=\"http:\/\/www.w3.org\/2000\/svg\">\n                    <path d=\"M23.725 5.33638C23.7248 5.3361 23.7245 5.33577 23.7242 5.33549L18.8256 0.460497C18.4586 0.0952939 17.865 0.096653 17.4997 0.463684C17.1345 0.830668 17.1359 1.42425 17.5028 1.7895L20.7918 5.06249H0.9375C0.419719 5.06249 0 5.48221 0 5.99999C0 6.51777 0.419719 6.93749 0.9375 6.93749H20.7917L17.5029 10.2105C17.1359 10.5757 17.1345 11.1693 17.4998 11.5363C17.865 11.9034 18.4587 11.9046 18.8256 11.5395L23.7242 6.66449C23.7245 6.66421 23.7248 6.66388 23.7251 6.6636C24.0923 6.29713 24.0911 5.70163 23.725 5.33638Z\"\n                          fill=\"#282828\"><\/path>\n                <\/svg>\n                <div class=\"shape\"><\/div>\n            <\/div>\n        <\/a>\n    <\/div>\n<\/div><!--[cta-banner title=\"Boost your <u>web development.<\/u>\" image=\"https:\/\/djangostars.com\/blog\/wp-content\/uploads\/2019\/05\/5_bg.png\" button=\"Learn more\" link=\"https:\/\/djangostars.com\/services\/web-development\/\" small_text=\"Get an experienced technical partner.\"]--><\/p>\n<h2>Final Thoughts<\/h2>\n<p>List Comprehensions are convenient options for creating lists based on other existing lists. They\u2019re much faster and more compact than other functions for creating lists, so even newbies who started learning Python recently must figure out how to use them correctly.<\/p>\n<p>Still, it\u2019s not a magic wand that makes your code perfect. Too long list comprehensions make code unreadable and hard to maintain.<\/p>\n<p>Learn more about using Python in commercial projects and<!--The very first thing that might scare or discourage a newbie programmer is the scale of educational material. The trick here is to treat each concept as an option offered by language, you\u2019re not expected to learn all the language concepts and modules all at once. There are always different ways to solve the same task. Take it as one more tool to get the job done.<b>F--> <b>feel free to <a href=\"https:\/\/djangostars.com\/get-in-touch\/\">contact Django Stars<\/a> if you need consulting or a dedicated team of Python developers.<\/b><!--[mailchimp-form]--><div class=\"dj-main-article-faq\" style=\"padding-top: 0px;\">\n\t\t<div class=\"dj-main-article-faq-title\">\n\t\tFrequently Asked Questions\n\t\t<\/div>\n\t\t<div class=\"dj-main-article-faq-items\">\n\t\t\t<div class=\"dj-main-article-faq-accordeon accordeon\"><dl>\n\t\t\t\t<dt>What is the difference between a list generator and list comprehension? \n\t\t\t\t<div class=\"cross\">\n\t\t\t\t<span><\/span>\n\t\t\t\t<span><\/span>\n\t\t\t\t<\/div>\n\t\t\t\t<\/dt>\n\t\t\t\t<dd>When a list comprehension is called, Python creates an entire list \u2014 all of its elements are stored in memory, allowing for quick access to them. The point of generators is not to store all the elements in memory. It saves memory but requires the entire list to be generated each time it is called to get the next element.<\/dd>\n\t\t\t<\/dl><dl>\n\t\t\t\t<dt>Are generators useful in Python? \n\t\t\t\t<div class=\"cross\">\n\t\t\t\t<span><\/span>\n\t\t\t\t<span><\/span>\n\t\t\t\t<\/div>\n\t\t\t\t<\/dt>\n\t\t\t\t<dd>Generators in Python are appropriate to use in cases where you need to process large amounts of data, memory is important (RAM needs careful handling), and speed is not critical. If speed is important and memory is not, then it is not necessary to use generators.<\/dd>\n\t\t\t<\/dl><dl>\n\t\t\t\t<dt>When to use list comprehension in Python? \n\t\t\t\t<div class=\"cross\">\n\t\t\t\t<span><\/span>\n\t\t\t\t<span><\/span>\n\t\t\t\t<\/div>\n\t\t\t\t<\/dt>\n\t\t\t\t<dd>List comprehension is the best way to enhance code readability and speed up its execution. Also, a list comprehension call in Python creates a new list without modification of the existing one, allowing using list comprehensions in a functional programming paradigm.<\/dd>\n\t\t\t<\/dl><dl>\n\t\t\t\t<dt>How to generate a list in Python? \n\t\t\t\t<div class=\"cross\">\n\t\t\t\t<span><\/span>\n\t\t\t\t<span><\/span>\n\t\t\t\t<\/div>\n\t\t\t\t<\/dt>\n\t\t\t\t<dd>To generate a list in Python, add a generator expression to the code using the following syntax: <b>generator<\/b> = (<b>expression<\/b> for <b>element<\/b> in <b>iterable<\/b> if <b>condition<\/b>). For example: <b>my_gen<\/b> = (<b>x**2<\/b> for <b>x<\/b> in <b>range(10)<\/b> if <b>x%2 == 0<\/b>). This differs from the Python list comprehension syntax by using parentheses instead of square brackets. <\/dd>\n\t\t\t<\/dl><dl>\n\t\t\t\t<dt>Are generators faster than lists in Python? \n\t\t\t\t<div class=\"cross\">\n\t\t\t\t<span><\/span>\n\t\t\t\t<span><\/span>\n\t\t\t\t<\/div>\n\t\t\t\t<\/dt>\n\t\t\t\t<dd>No. The advantage of a Python generator is that it doesn't store the list in RAM. Instead, it remembers the state. But recalculation every time the function is called takes more time comparing access to any element in the regular Python list.<\/dd>\n\t\t\t<\/dl><\/div>\n\t\t\t<\/div>\n\t\t<\/div><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Do you know the difference between the following syntax? [x for x in range(5)] (x for x in range(5)) tuple(range(5)) This is exactly what differentiates Python from other languages and makes Python the best programming language. Coming from functional languages and being implemented in Python from early days, list comprehension became its distinctive feature. This [&hellip;]<\/p>\n","protected":false},"author":30,"featured_media":3544,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[44],"tags":[30],"class_list":["post-98","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python-django","tag-backend"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Software Development Blog &amp; IT Tech Insights | Django Stars<\/title>\n<meta name=\"description\" content=\"The difference between list comprehensions and generator expressions \u26a1 Simple examples from basic to complex concepts \u26a1 Benefits of list comprehensions\" \/>\n<link rel=\"canonical\" href=\"https:\/\/djangostars.com\/blog\/wp-json\/wp\/v2\/posts\/98\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Generator Expression and List Comprehensions | Django Stars\" \/>\n<meta property=\"og:description\" content=\"The difference between list comprehensions and generator expressions \u26a1 Simple examples from basic to complex concepts \u26a1 Benefits of list comprehensions\" \/>\n<meta property=\"og:url\" content=\"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/\" \/>\n<meta property=\"og:site_name\" content=\"Software Development Blog &amp; IT Tech Insights | Django Stars\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/djangostars\/\" \/>\n<meta property=\"article:author\" content=\"https:\/\/www.facebook.com\/soner.mcayberk\" \/>\n<meta property=\"article:published_time\" content=\"2017-01-13T15:43:07+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-10-28T14:59:07+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/djangostars.com\/blog\/wp-content\/uploads\/2021\/12\/Python-List-Comprehensions-and-Generator-Expressions.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1440\" \/>\n\t<meta property=\"og:image:height\" content=\"620\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Soner Ayberk\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@djangostars\" \/>\n<meta name=\"twitter:site\" content=\"@djangostars\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Soner Ayberk\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"7 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/\"},\"author\":{\"name\":\"Soner Ayberk\",\"@id\":\"https:\/\/djangostars.com\/blog\/#\/schema\/person\/3ce5a3a756f478ea6fdcf41d1eb56313\"},\"headline\":\"List Comprehensions in Python and Generator Expressions\",\"datePublished\":\"2017-01-13T15:43:07+00:00\",\"dateModified\":\"2024-10-28T14:59:07+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/\"},\"wordCount\":1497,\"commentCount\":0,\"image\":{\"@id\":\"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/djangostars.com\/blog\/wp-content\/uploads\/2021\/12\/Python-List-Comprehensions-and-Generator-Expressions.jpg\",\"keywords\":[\"Backend\"],\"articleSection\":[\"Python &amp; Django\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/\",\"url\":\"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/\",\"name\":\"Python Generator Expression and List Comprehensions | Django Stars\",\"isPartOf\":{\"@id\":\"https:\/\/djangostars.com\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/djangostars.com\/blog\/wp-content\/uploads\/2021\/12\/Python-List-Comprehensions-and-Generator-Expressions.jpg\",\"datePublished\":\"2017-01-13T15:43:07+00:00\",\"dateModified\":\"2024-10-28T14:59:07+00:00\",\"author\":{\"@id\":\"https:\/\/djangostars.com\/blog\/#\/schema\/person\/3ce5a3a756f478ea6fdcf41d1eb56313\"},\"description\":\"The difference between list comprehensions and generator expressions \u26a1 Simple examples from basic to complex concepts \u26a1 Benefits of list comprehensions\",\"breadcrumb\":{\"@id\":\"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/#primaryimage\",\"url\":\"https:\/\/djangostars.com\/blog\/wp-content\/uploads\/2021\/12\/Python-List-Comprehensions-and-Generator-Expressions.jpg\",\"contentUrl\":\"https:\/\/djangostars.com\/blog\/wp-content\/uploads\/2021\/12\/Python-List-Comprehensions-and-Generator-Expressions.jpg\",\"width\":1440,\"height\":620,\"caption\":\"Python-List-Comprehensions-and-Generator-Expressions\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/djangostars.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"List Comprehensions in Python and Generator Expressions\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/djangostars.com\/blog\/#website\",\"url\":\"https:\/\/djangostars.com\/blog\/\",\"name\":\"Software Development Blog &amp; IT Tech Insights | Django Stars\",\"description\":\"Welcome behind the scenes of software product development. We share our best practices, tech solutions, management tips, and every useful insight we\u2018ve got while working on our projects.\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/djangostars.com\/blog\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/djangostars.com\/blog\/#\/schema\/person\/3ce5a3a756f478ea6fdcf41d1eb56313\",\"name\":\"Soner Ayberk\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/djangostars.com\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/c66a1f353ba4845419cbd88bd99e6f285dbf8282efe028def0b7cd90cdc18cb2?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/c66a1f353ba4845419cbd88bd99e6f285dbf8282efe028def0b7cd90cdc18cb2?s=96&d=mm&r=g\",\"caption\":\"Soner Ayberk\"},\"sameAs\":[\"https:\/\/www.facebook.com\/soner.mcayberk\",\"https:\/\/www.linkedin.com\/in\/soner-ayberk-030ab6b6\/\"],\"url\":\"https:\/\/djangostars.com\/blog\/author\/soner-ayberk\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Software Development Blog &amp; IT Tech Insights | Django Stars","description":"The difference between list comprehensions and generator expressions \u26a1 Simple examples from basic to complex concepts \u26a1 Benefits of list comprehensions","canonical":"https:\/\/djangostars.com\/blog\/wp-json\/wp\/v2\/posts\/98","og_locale":"en_US","og_type":"article","og_title":"Python Generator Expression and List Comprehensions | Django Stars","og_description":"The difference between list comprehensions and generator expressions \u26a1 Simple examples from basic to complex concepts \u26a1 Benefits of list comprehensions","og_url":"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/","og_site_name":"Software Development Blog &amp; IT Tech Insights | Django Stars","article_publisher":"https:\/\/www.facebook.com\/djangostars\/","article_author":"https:\/\/www.facebook.com\/soner.mcayberk","article_published_time":"2017-01-13T15:43:07+00:00","article_modified_time":"2024-10-28T14:59:07+00:00","og_image":[{"width":1440,"height":620,"url":"https:\/\/djangostars.com\/blog\/wp-content\/uploads\/2021\/12\/Python-List-Comprehensions-and-Generator-Expressions.jpg","type":"image\/jpeg"}],"author":"Soner Ayberk","twitter_card":"summary_large_image","twitter_creator":"@djangostars","twitter_site":"@djangostars","twitter_misc":{"Written by":"Soner Ayberk","Est. reading time":"7 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/#article","isPartOf":{"@id":"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/"},"author":{"name":"Soner Ayberk","@id":"https:\/\/djangostars.com\/blog\/#\/schema\/person\/3ce5a3a756f478ea6fdcf41d1eb56313"},"headline":"List Comprehensions in Python and Generator Expressions","datePublished":"2017-01-13T15:43:07+00:00","dateModified":"2024-10-28T14:59:07+00:00","mainEntityOfPage":{"@id":"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/"},"wordCount":1497,"commentCount":0,"image":{"@id":"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/#primaryimage"},"thumbnailUrl":"https:\/\/djangostars.com\/blog\/wp-content\/uploads\/2021\/12\/Python-List-Comprehensions-and-Generator-Expressions.jpg","keywords":["Backend"],"articleSection":["Python &amp; Django"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/","url":"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/","name":"Python Generator Expression and List Comprehensions | Django Stars","isPartOf":{"@id":"https:\/\/djangostars.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/#primaryimage"},"image":{"@id":"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/#primaryimage"},"thumbnailUrl":"https:\/\/djangostars.com\/blog\/wp-content\/uploads\/2021\/12\/Python-List-Comprehensions-and-Generator-Expressions.jpg","datePublished":"2017-01-13T15:43:07+00:00","dateModified":"2024-10-28T14:59:07+00:00","author":{"@id":"https:\/\/djangostars.com\/blog\/#\/schema\/person\/3ce5a3a756f478ea6fdcf41d1eb56313"},"description":"The difference between list comprehensions and generator expressions \u26a1 Simple examples from basic to complex concepts \u26a1 Benefits of list comprehensions","breadcrumb":{"@id":"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/#primaryimage","url":"https:\/\/djangostars.com\/blog\/wp-content\/uploads\/2021\/12\/Python-List-Comprehensions-and-Generator-Expressions.jpg","contentUrl":"https:\/\/djangostars.com\/blog\/wp-content\/uploads\/2021\/12\/Python-List-Comprehensions-and-Generator-Expressions.jpg","width":1440,"height":620,"caption":"Python-List-Comprehensions-and-Generator-Expressions"},{"@type":"BreadcrumbList","@id":"https:\/\/djangostars.com\/blog\/list-comprehensions-and-generator-expressions\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/djangostars.com\/blog\/"},{"@type":"ListItem","position":2,"name":"List Comprehensions in Python and Generator Expressions"}]},{"@type":"WebSite","@id":"https:\/\/djangostars.com\/blog\/#website","url":"https:\/\/djangostars.com\/blog\/","name":"Software Development Blog &amp; IT Tech Insights | Django Stars","description":"Welcome behind the scenes of software product development. We share our best practices, tech solutions, management tips, and every useful insight we\u2018ve got while working on our projects.","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/djangostars.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/djangostars.com\/blog\/#\/schema\/person\/3ce5a3a756f478ea6fdcf41d1eb56313","name":"Soner Ayberk","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/djangostars.com\/blog\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/c66a1f353ba4845419cbd88bd99e6f285dbf8282efe028def0b7cd90cdc18cb2?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/c66a1f353ba4845419cbd88bd99e6f285dbf8282efe028def0b7cd90cdc18cb2?s=96&d=mm&r=g","caption":"Soner Ayberk"},"sameAs":["https:\/\/www.facebook.com\/soner.mcayberk","https:\/\/www.linkedin.com\/in\/soner-ayberk-030ab6b6\/"],"url":"https:\/\/djangostars.com\/blog\/author\/soner-ayberk\/"}]}},"_links":{"self":[{"href":"https:\/\/djangostars.com\/blog\/wp-json\/wp\/v2\/posts\/98","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/djangostars.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/djangostars.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/djangostars.com\/blog\/wp-json\/wp\/v2\/users\/30"}],"replies":[{"embeddable":true,"href":"https:\/\/djangostars.com\/blog\/wp-json\/wp\/v2\/comments?post=98"}],"version-history":[{"count":29,"href":"https:\/\/djangostars.com\/blog\/wp-json\/wp\/v2\/posts\/98\/revisions"}],"predecessor-version":[{"id":8402,"href":"https:\/\/djangostars.com\/blog\/wp-json\/wp\/v2\/posts\/98\/revisions\/8402"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/djangostars.com\/blog\/wp-json\/wp\/v2\/media\/3544"}],"wp:attachment":[{"href":"https:\/\/djangostars.com\/blog\/wp-json\/wp\/v2\/media?parent=98"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/djangostars.com\/blog\/wp-json\/wp\/v2\/categories?post=98"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/djangostars.com\/blog\/wp-json\/wp\/v2\/tags?post=98"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}