Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] List Comprehension in Python

#1
[Tut] List Comprehension in Python

<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload='{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;1646570&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;2&quot;,&quot;legendonly&quot;:&quot;&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;starsonly&quot;:&quot;&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\/5 - (2 votes)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;title&quot;:&quot;List Comprehension in Python&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}'>
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (2 votes) </div>
</p></div>
<h2 class="wp-block-heading">Understanding List Comprehension</h2>
<p>List comprehension is a concise way to create lists in Python. They offer a shorter syntax to achieve the same result as using a traditional <code>for</code> loop and a conditional statement. List comprehensions make your code more readable and efficient by condensing multiple lines of code into a single line.</p>
<p>The basic syntax for a list comprehension is: </p>
<pre class="wp-block-preformatted"><code>new_list = [expression for element in iterable if condition]</code></pre>
<p class="has-global-color-8-background-color has-background">Here, the <code>expression</code> is applied to each <code>element</code> in the <code><a href="https://blog.finxter.com/iterators-iterables-and-itertools/">iterable</a></code> (e.g., a list or a range), and the result is appended to the <code>new_list</code> if the optional <code>condition</code> is <code>True</code>. If the condition is not provided, all elements will be included in the new list.</p>
<p>Let’s look at an example. Suppose you want to <a href="https://blog.finxter.com/python-create-list-from-1-to-n/">create a list of squares</a> for all even numbers between 0 and 10. Using a list comprehension, you can write:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">squares = [x**2 for x in range(11) if x % 2 == 0]
</pre>
<p>This <a href="https://blog.finxter.com/python-one-line-x/">single line of code</a> generates the list of squares, <code>[0, 4, 16, 36, 64, 100]</code>. It’s more concise and easier to read compared to using a traditional <code>for</code> loop:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">squares = []
for x in range(11): if x % 2 == 0: squares.append(x**2)
</pre>
<p>You can watch my explainer video on list comprehension here:</p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/list-comprehension-in-python/"><img decoding="async" src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F9qsq2Vf48W8%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<p class="has-global-color-8-background-color has-background">List comprehensions can also include <a href="https://towardsdatascience.com/4-tips-to-master-python-list-comprehensions-616defe70738">multiple conditions</a> and <a href="https://stackoverflow.com/questions/38408991/understanding-list-comprehensions-in-python">nested loops</a>. </p>
<p>For example, you can create a list of all numbers divisible by both 3 and 5 between 1 and 100 with the following code:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">divisible = [num for num in range(1, 101) if num % 3 == 0 and num % 5 == 0]
</pre>
<p>In this case, the resulting list will be <code>[15, 30, 45, 60, 75, 90]</code>.</p>
<p class="has-global-color-8-background-color has-background">One more advanced feature of Python list comprehensions is the ability to include <a href="https://blog.finxter.com/if-then-else-in-one-line-python/">conditional expressions</a> directly in the expression part, rather than just in the condition. </p>
<p>For example, you can create a list of “even” and “odd” strings based on a range of numbers like this:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">even_odd = ["even" if x % 2 == 0 else "odd" for x in range(6)]
</pre>
<p>This code generates the list <code>["even", "odd", "even", "odd", "even", "odd"]</code>.</p>
<p>If you want to learn to write more concise Python code, check out my book: <img decoding="async" src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p>
<p><strong>Check out my new Python book <a title="https://amzn.to/2WAYeJE" href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener">Python One-Liners</a></strong> (Amazon Link).</p>
<p>If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a <strong>single line of Python code.</strong> But it’s also an <strong>introduction to computer science</strong>, data science, machine learning, and algorithms. <strong><em>The universe in a single line of Python!</em></strong></p>
<div class="wp-block-image">
<figure class="aligncenter"><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noopener noreferrer"><img decoding="async" fetchpriority="high" width="215" height="283" src="https://blog.finxter.com/wp-content/uploads/2020/02/image-1.png" alt="" class="wp-image-5969"/></a></figure>
</div>
<p>The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco). </p>
<p><strong>Publisher Link</strong>: <a href="https://nostarch.com/pythononeliners" target="_blank" rel="noreferrer noopener">https://nostarch.com/pythononeliners</a></p>
<h2 class="wp-block-heading">Creating New Lists</h2>
<p>List comprehensions provide a concise way to make new lists by iterating through an existing list or other iterable object. They are more time and space-efficient than traditional <code><a href="https://blog.finxter.com/python-one-line-for-loop-a-simple-tutorial/">for</a></code> loops and offer a cleaner syntax.</p>
<p>A basic example of list comprehension is creating a <a href="https://blog.finxter.com/11-ways-to-create-a-list-of-even-numbers-in-python/">list of even numbers</a>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">even_numbers = [x*2 for x in range(5)] # Output: [0, 2, 4, 6, 8]
</pre>
<p>This creates a new list by multiplying each element within the <code><a href="https://blog.finxter.com/python-range-function/">range(5)</a></code> function by 2. This compact syntax allows you to define a new list in a <a href="https://pythononeliners.com/">single line</a>, making your code cleaner and easier to read.</p>
<p>You can also include a conditional statement within the list comprehension:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">even_squares = [x**2 for x in range(10) if x % 2 == 0] # Output: [0, 4, 16, 36, 64]
</pre>
<p>This example creates a new list of even squares from 0 to 64 by using an <code>if</code> statement to <a href="https://blog.finxter.com/python-filter/">filter out the odd numbers</a>. List comprehensions can also be used to create lists from other iterable objects like strings, tuples, or arrays. </p>
<p>For example, extracting vowels from a string:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">text = "List comprehensions in Python"
vowels = [c for c in text if c.lower() in 'aeiou'] # Output: ['i', 'o', 'e', 'e', 'o', 'i', 'o', 'i', 'o']
</pre>
<p>To <a href="https://blog.finxter.com/how-to-create-a-python-list-of-size-n/">create a Python list of a specific size</a>, you can use the multiplication approach within your list comprehension:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">placeholder_list = [None] * 5 # Output: [None, None, None, None, None]
</pre>
<p>This will create a list with five <code>None</code> elements. You can then replace them as needed, like <code>placeholder_list[2] = 42</code>, resulting in <code>[None, None, 42, None, None]</code>.</p>
<h2 class="wp-block-heading">Filtering and Transforming Lists</h2>
<p><strong>List comprehensions in Python provide a concise way to filter and transform values within an existing list.</strong></p>
<p class="has-global-color-8-background-color has-background">Filtering a list involves selecting items that meet a certain condition. You can achieve this using list comprehensions by specifying a condition at the end of the expression. </p>
<p>For example, to create a new list containing only even numbers from an existing list, you would write:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_numbers = [num for num in numbers if num % 2 == 0]
</pre>
<p>In this case, the condition is <code>num % 2 == 0</code>. The list comprehension iterates over each item in the <code>numbers</code> list and only includes items where the condition is true.</p>
<p>You can watch my video on <a href="https://blog.finxter.com/how-to-filter-a-list-in-python/">filtering lists</a> here:</p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/list-comprehension-in-python/"><img decoding="async" src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F3nG4TLkqzf8%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<p class="has-global-color-8-background-color has-background">Aside from filtering, <strong>list comprehensions can also transform items in a list</strong>. You can achieve this by altering the expression at the beginning of the list comprehension. </p>
<p>For example, to create a list of squares from an existing list, you can use the following code:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">squares = [num ** 2 for num in numbers]
</pre>
<p>Here, the expression <code>num ** 2</code> transforms each item in the list by squaring it. The <code>squares</code> list will now contain the squared values of the original <code>numbers</code> list.</p>
<p>By combining filtering and transformation, you can achieve even more powerful results in a single, concise statement. </p>
<p>For instance, to create a new list containing the squares of only the even numbers from an existing list, you can write:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">even_squares = [num ** 2 for num in numbers if num % 2 == 0]
</pre>
<p>In this example, we simultaneously filter out odd numbers and square the remaining even numbers.</p>
<p>To further explore list comprehensions, check out these resources on </p>
<ul>
<li><a href="https://blog.finxter.com/python-list-find-element/">finding an element in a list</a>,</li>
<li><a href="https://blog.finxter.com/how-to-get-specific-elements-from-a-list/">getting specific elements from a list</a>,</li>
<li><a href="https://blog.finxter.com/how-to-filter-a-list-in-python/">filtering lists in Python</a>, and </li>
<li><a href="https://blog.finxter.com/extract-elements-from-python-lists/">extracting elements from Python lists</a>.</li>
</ul>
<h2 class="wp-block-heading">Code Optimization and Readability</h2>
<p>List comprehensions in Python provide a way to create a new list by filtering and transforming elements of an existing list while significantly enhancing code readability. They enable you to create powerful functionality within a <strong><a href="https://blog.finxter.com/python-one-line-generator/">single line of code</a></strong>. Compared to traditional <code>for</code> loops, list comprehensions are more concise and generally preferred in terms of readability.</p>
<p>Here’s an example of using a list comprehension to create a list containing the squares of even numbers in a given range:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">even_squares = [x ** 2 for x in range(10) if x % 2 == 0]
</pre>
<p>This single line of code replaces a multiline <code>for</code> loop as shown below:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">even_squares = []
for x in range(10): if x % 2 == 0: even_squares.append(x ** 2)
</pre>
<p>As you can see, the list comprehension is more compact and easier to understand. In addition, it often results in improved performance. List comprehensions are also useful for tasks such as filtering elements, transforming data, and nesting loops.</p>
<p>Here’s another example – creating a matrix transpose using nested list comprehensions:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transpose = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
</pre>
<p>This code snippet is equivalent to the nested <code>for</code> loop version:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">transpose = []
for i in range(len(matrix[0])): row_list = [] for row in matrix: row_list.append(row[i]) transpose.append(row_list)
</pre>
<p>While using list comprehensions, be mindful of possible downsides, including loss of readability if the expression becomes too complex. To maintain code clarity, it is crucial to strike the right balance between brevity and simplicity.</p>
<h2 class="wp-block-heading">List Comprehensions with Different Data Types</h2>
<p>List comprehensions work with various data types, such as strings, tuples, dictionaries, and sets.</p>
<p>For example, you can use list comprehensions to perform <a href="https://www.learndatasci.com/solutions/python-list-comprehension/">mathematical operations</a> on list elements. Given a list of integers, you can easily square each element using a single line of code:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">num_list = [2, 4, 6]
squared_list = [x**2 for x in num_list]
</pre>
<p>Handling <a href="https://datagy.io/list-comprehensions-in-python/">strings</a> is also possible with list comprehensions. When you want to create a list of the first letters of a list of words, use the following syntax:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">words = ["apple", "banana", "cherry"]
first_letters = [word[0] for word in words]
</pre>
<p>Working with <a href="https://towardsdatascience.com/11-examples-to-master-python-list-comprehensions-33c681b56212">tuples</a> is very similar to lists. You can extract specific elements from a list of tuples, like this:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">tuple_list = [(1, 2), (3, 4), (5, 6)]
first_elements = [t[0] for t in tuple_list]
</pre>
<p>Additionally, you can use list comprehensions with dictionaries. If you have a <a href="https://www.programiz.com/python-programming/list-comprehension">dictionary</a> and want to create a new one where the keys are the original keys and the values are the squared values from the original dictionary, use the following code:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">input_dict = {"a": 1, "b": 2, "c": 3}
squared_dict = {key: value**2 for key, value in input_dict.items()}
</pre>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/list-comprehension-in-python/"><img decoding="async" src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FTlEC5Jx72Uc%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<p><img decoding="async" src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>:</p>
<ul>
<li><a href="https://blog.finxter.com/brackets-a-simple-introduction-to-set-comprehension-in-python/">A Simple Introduction to Set Comprehension in Python</a></li>
<li><a href="https://blog.finxter.com/python-dictionary-comprehension/">Python Dictionary Comprehension: A Powerful One-Liner Tutorial</a></li>
</ul>
<p>Lastly, list comprehensions support sets as well. When you need to create a <a href="https://www.geeksforgeeks.org/python-list-comprehension/">set</a> with the squared elements from another set, apply the following code:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">input_set = {1, 2, 3, 4}
squared_set = {x**2 for x in input_set}
</pre>
<p><img decoding="async" src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/python-generator-expressions/">Python Generator Expressions</a></p>
<h2 class="wp-block-heading">Using Functions and Variables in List Comprehensions</h2>
<p>List comprehensions in Python are a concise and powerful way to create new lists by iterating over existing ones. They provide a more readable alternative to using <code>for</code> loops and can <a href="https://blog.finxter.com/how-to-add-multiple-values-to-a-key-in-a-python-dictionary/">easily add multiple values</a> to specific keys in a dictionary.</p>
<p>When it comes to using functions and variables in list comprehensions, it’s important to keep the code clear and efficient. Let’s see how to incorporate functions, variables, and other elements mentioned earlier:</p>
<p><strong>Using Functions in List Comprehensions</strong> You can apply a function to each item in the list using a comprehension. Here’s an example with the <code><a href="https://blog.finxter.com/python-string-upper/">upper()</a></code> method:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">letters = ['a', 'b', 'c', 'd']
upper_letters = [x.upper() for x in letters]
</pre>
<p>This comprehension will return a new list containing the uppercase versions of each letter. Any valid function can replace <code>x.upper()</code> to apply different effects on the input list.</p>
<p><strong>Utilizing Variables in List Comprehensions</strong> With variables, you can use them as a <a href="https://blog.finxter.com/python-how-to-count-elements-in-a-list-with-collections-counter/">counter</a> or a condition. For example, a list comprehension with a counter:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">squares = [i**2 for i in range(1, 6)]
</pre>
<p>This comprehension creates a list of squared numbers from 1 to 5. The variable <code>i</code> is a counter that iterates through the <code><a href="https://blog.finxter.com/python-range-function/">range()</a></code> function.</p>
<p>For a more complex example, let’s say we want to filter out odd numbers from a list using the <a href="https://blog.finxter.com/python-in-place-modulo-operator/">modulo <code>%</code> operator</a>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_numbers = [x for x in numbers if x % 2 == 0]
</pre>
<p>In this case, the variable <code>x</code> represents the current element being manipulated during the iteration, and it is used in the condition <code>x % 2 == 0</code> to ensure we only keep even numbers.</p>
<h2 class="wp-block-heading">Working with Nested List Comprehensions</h2>
<p>Nested list comprehensions in Python are a versatile and powerful feature that allows you to create new lists by applying an expression to an existing <a href="https://blog.finxter.com/list-comprehension-python-list-of-lists/">list of lists</a>. This is particularly useful for updating or traversing nested sequences in a concise and readable manner.</p>
<p>I created a video on nested list comprehensions here: <img decoding="async" src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/list-comprehension-in-python/"><img decoding="async" src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FaBC0VhpXkOQ%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<p>A nested list comprehension consists of a list comprehension inside another list comprehension, much like how nested loops work. It enables you to iterate over nested sequences and apply operations to each element.</p>
<p>For example, consider a matrix represented as a list of lists:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]
]
</pre>
<p>To calculate the square of each element in the matrix using nested list comprehensions, you can write:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">squared_matrix = [[x**2 for x in row] for row in matrix]
</pre>
<p>This code is equivalent to the following nested <code>for</code> loop:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">squared_matrix = []
for row in matrix: squared_row = [] for x in row: squared_row.append(x**2) squared_matrix.append(squared_row)
</pre>
<p>As you can see, the nested list comprehension version is much more concise and easier to read.</p>
<p>Python supports various sequences like lists, tuples, and dictionaries. You can use nested list comprehensions to create different data structures by combining them. For instance, you can convert the <code>matrix</code> above into a dictionary where keys are the original numbers and values are their squares:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">matrix_dict = {x: x**2 for row in matrix for x in row}
</pre>
<p>This generates a dictionary that looks like:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
</pre>
</p>
<h2 class="wp-block-heading">Advanced List Comprehension Techniques</h2>
<p>List comprehension is a powerful feature in Python that allows you to quickly create new lists based on existing <a href="https://blog.finxter.com/iterators-iterables-and-itertools/">iterables</a>. They provide a concise and efficient way of creating new lists with a few lines of code. </p>
<p>The first advanced technique to consider is using <code>range()</code> with index. By utilizing the <code>range(len(...))</code> function, you can iterate over all the items in a given <a href="https://blog.finxter.com/how-to-use-rangelen-in-python/">iterable</a>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">numbers = [1, 2, 3, 4, 5]
squares = [number ** 2 for number in numbers]
</pre>
<p>In addition to creating new lists, you can also use conditional statements in list comprehensions for more control over the output. </p>
<p>For example, if you want to create a new list with only the even numbers from an existing list, you can use a condition like this:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [num for num in numbers if num % 2 == 0]
</pre>
<p>Another useful feature is the access of elements in an iterable using their index. This method enables you to modify the output based on the position of the elements:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">words = ["apple", "banana", "cherry", "date"]
capitals = [word.capitalize() if i % 2 == 0 else word for i, word in enumerate(words)]
</pre>
<p>In this example, the <code><a href="https://blog.finxter.com/python-enumerate/">enumerate()</a></code> function is used to get both the index (i) and the element (word). The even-indexed words are capitalized, and the others remain unchanged.</p>
<p>Moreover, you can combine multiple iterables using the <code><a href="https://blog.finxter.com/how-can-i-join-two-lists-in-python-a-quick-guide/">zip()</a></code> function. This technique allows you to access elements from different lists simultaneously, creating new lists based on matched pairs.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">x = [1, 2, 3]
y = [4, 5, 6]
combined = [a + b for a, b in zip(x, y)]
</pre>
</p>
<h2 class="wp-block-heading">Frequently Asked Questions</h2>
<h3 class="wp-block-heading">What is the syntax for list comprehensions with if-else statements?</h3>
<p>List comprehensions allow you to build lists in a concise way. To include an if-else statement while constructing a list, use the following syntax:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">new_list = [expression_if_true if condition else expression_if_false for item in iterable]
</pre>
<p>For example, if you want to create a list of numbers, where even numbers are squared and odd numbers remain unchanged:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">numbers = [1, 2, 3, 4, 5]
new_list = [number ** 2 if number % 2 == 0 else number for number in numbers]
</pre>
<h3 class="wp-block-heading">How do you create a dictionary using list comprehension?</h3>
<p>You can create a dictionary using a dict comprehension, which is similar to a list comprehension. The syntax is:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">new_dict = {key_expression: value_expression for item in iterable}
</pre>
<p>For example, creating a dictionary with square values as keys and their roots as values:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">squares = {num ** 2: num for num in range(1, 6)}
</pre>
<h3 class="wp-block-heading">How can you filter a list using list comprehensions?</h3>
<p>Filtering a list using list comprehensions involves combining the basic syntax with a condition. The syntax is:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">filtered_list = [expression for item in iterable if condition]
</pre>
<p>For example, filtering out even numbers from a given list:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">numbers = [1, 2, 3, 4, 5]
even_numbers = [number for number in numbers if number % 2 == 0]
</pre>
<h3 class="wp-block-heading">What is the method to use list comprehension with strings?</h3>
<p>List comprehensions can be used with any iterable, including strings. To create a list of characters from a string using list comprehension:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">text = "Hello, World!"
char_list = [char for char in text]
</pre>
<h3 class="wp-block-heading">How do you combine two lists using list comprehensions?</h3>
<p>To combine two lists using list comprehensions, use a nested loop. Here’s the syntax:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">combined_list = [expression for item1 in list1 for item2 in list2]
</pre>
<p>For example, combining two lists containing names and ages:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
combined = [f"{name} is {age} years old" for name in names for age in ages]
</pre>
<h3 class="wp-block-heading">What are the multiple conditions in a list comprehension?</h3>
<p>When using multiple conditions in a list comprehension, you can have multiple <code>if</code> statements after the expression. The syntax is:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">new_list = [expression for item in iterable if condition1 if condition2]
</pre>
<p>For example, creating a list of even numbers greater than 10:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">numbers = list(range(1, 20))
result = [number for number in numbers if number % 2 == 0 if number > 10]
</pre>
<p><img decoding="async" src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/list-comprehension/">List Comprehension in Python — A Helpful Illustrated Guide</a></p>
<h2 class="wp-block-heading">Python One-Liners Book: Master the Single Line First!</h2>
<p><strong>Python programmers will improve their computer science skills with these useful one-liners.</strong></p>
<div class="wp-block-image">
<figure class="aligncenter size-medium is-resized"><a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noopener noreferrer"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-1024x944.jpg" alt="Python One-Liners" class="wp-image-10007" width="512" height="472" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x277.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x708.jpg 768w" sizes="(max-width: 512px) 100vw, 512px" /></a></figure>
</div>
<p><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE"><em>Python One-Liners</em> </a>will teach you how to read and write “one-liners”: <strong><em>concise statements of useful functionality packed into a single line of code. </em></strong>You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.</p>
<p>The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms. </p>
<p>Detailed explanations of one-liners introduce <strong><em>key computer science concepts </em></strong>and<strong><em> boost your coding and analytical skills</em></strong>. You’ll learn about advanced Python features such as <em><strong>list comprehension</strong></em>, <strong><em>slicing</em></strong>, <strong><em>lambda functions</em></strong>, <strong><em>regular expressions</em></strong>, <strong><em>map </em></strong>and <strong><em>reduce </em></strong>functions, and <strong><em>slice assignments</em></strong>. </p>
<p>You’ll also learn how to:</p>
<ul>
<li>Leverage data structures to <strong>solve real-world problems</strong>, like using Boolean indexing to find cities with above-average pollution</li>
<li>Use <strong>NumPy basics</strong> such as <em>array</em>, <em>shape</em>, <em>axis</em>, <em>type</em>, <em>broadcasting</em>, <em>advanced indexing</em>, <em>slicing</em>, <em>sorting</em>, <em>searching</em>, <em>aggregating</em>, and <em>statistics</em></li>
<li>Calculate basic <strong>statistics </strong>of multidimensional data arrays and the K-Means algorithms for unsupervised learning</li>
<li>Create more <strong>advanced regular expressions</strong> using <em>grouping </em>and <em>named groups</em>, <em>negative lookaheads</em>, <em>escaped characters</em>, <em>whitespaces, character sets</em> (and <em>negative characters sets</em>), and <em>greedy/nongreedy operators</em></li>
<li>Understand a wide range of <strong>computer science topics</strong>, including <em>anagrams</em>, <em>palindromes</em>, <em>supersets</em>, <em>permutations</em>, <em>factorials</em>, <em>prime numbers</em>, <em>Fibonacci </em>numbers, <em>obfuscation</em>, <em>searching</em>, and <em>algorithmic sorting</em></li>
</ul>
<p>By the end of the book, you’ll know how to <strong><em>write Python at its most refined</em></strong>, and create concise, beautiful pieces of “Python art” in merely a single line.</p>
<p><strong><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE"><em>Get your Python One-Liners on Amazon!!</em></a></strong></p>
<p>The post <a rel="nofollow" href="https://blog.finxter.com/list-comprehension-in-python/">List Comprehension in Python</a> appeared first on <a rel="nofollow" href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
</div>


https://www.sickgaming.net/blog/2023/08/...in-python/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016