Create an account


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

#1
How Does Nested List Comprehension Work in Python?

<div><p><strong><em>Nested List Comprehension</em></strong>—what does it even mean?</p>
<p> <iframe height="400px" width="100%" src="https://repl.it/@finxter/nestedlistcomprehension?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"></iframe> </p>
<p>There are three equally interpretations of this term:</p>
<ul>
<li>Coming from a computer science background, I was assuming that “nested list comprehension” refers to the creation of a list of lists. In other words: <strong>How to create a nested list with list comprehension?</strong></li>
<li>But after a bit of research, I learned that there is a second interpretation of nested list comprehension: <strong>How to use a nested for loop in the list comprehension?</strong></li>
<li>A few months later, I realized that some people use “nested list comprehension” to mean the use of a list comprehension statement as expression within a list comprehension statement. In other words: <strong>How to use a list comprehension statement within a list comprehension statement?</strong> (Watch the video to learn about this third interpretation.)</li>
</ul>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="Python One-Liner Trick 9 - Nested List Comprehension" width="1400" height="788" src="https://www.youtube.com/embed/aBC0VhpXkOQ?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<h3>How to Create a Nested List with List Comprehension?</h3>
<p>It is possible to create a nested list with list comprehension in Python. What is a nested list? It’s a list of lists. Here is an example:</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="">## Nested List Comprehension
lst = [[x for x in range(5)] for y in range(3)]
print(lst)
# [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]</pre>
<p>As you can see, we create a list with three elements. Each list element is a list by itself. </p>
<p>Everything becomes clear when we go back to our magic formula of list comprehension: <code>[ expression + context]</code>. The expression part generates a new list consisting of 5 integers. The context part repeats this three times. Hence, each of the three nested lists has five elements. </p>
<p>If you are an advanced programmer, you may ask whether there is some aliasing going on here. Aliasing in this context means that the three list elements point to the same list <code>[0, 1, 2, 3, 4]</code>. This is not the case because each expression is evaluated separately, a new list is created for each of the three context executions. This is nicely demonstrated in this code snippet:</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="">l[0].append(5)
print(l)
# [[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
# ... and not [[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5]]</pre>
<h3>How to Use a Nested For Loop in the List Comprehension?</h3>
<p>To be frank, this is super-simple stuff. Do you remember the formula of list comprehension (= ‘[‘ + expression + context + ‘]’)? </p>
<p>The context is an arbitrary complex restriction construct of for loops and if restrictions with the goal of specifying the data items on which the expression should be applied.</p>
<p>In the expression, you can use any variable you define within a for loop in the context. Let’s have a look at an example.</p>
<p>Suppose you want to use list comprehension to make this code more concise (for example, you want to find all possible pairs of users in your social network application):</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=""># BEFORE
users = ["John", "Alice", "Ann", "Zach"]
pairs = []
for x in users: for y in users: if x != y: pairs.append((x,y))
print(pairs)
#[('John', 'Alice'), ('John', 'Ann'), ('John', 'Zach'), ('Alice', 'John'), ('Alice', 'Ann'), ('Alice', 'Zach'), ('Ann', 'John'), ('Ann', 'Alice'), ('Ann', 'Zach'), ('Zach', 'John'), ('Zach', 'Alice'), ('Zach', 'Ann')]</pre>
<p>Now, this code is a mess! How can we fix it? Simply use nested 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=""># AFTER
pairs = [(x,y) for x in users for y in users if x!=y]
print(pairs)
# [('John', 'Alice'), ('John', 'Ann'), ('John', 'Zach'), ('Alice', 'John'), ('Alice', 'Ann'), ('Alice', 'Zach'), ('Ann', 'John'), ('Ann', 'Alice'), ('Ann', 'Zach'), ('Zach', 'John'), ('Zach', 'Alice'), ('Zach', 'Ann')]</pre>
<p>As you can see, we are doing exactly the same thing as with un-nested list comprehension. The only difference is to write the two for loops and the if statement in a single line within the list notation <code>[]</code>.</p>
<h2>How to Use a List Comprehension Statement Within a List Comprehension Statement?</h2>
<p>Our goal is to solve the following problem: given a multiline string, create a list of lists—each consisting of all the words in a line that have more than three characters.</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="">## Data
text = '''
Call me Ishmael. Some years ago - never mind how long precisely - having
little or no money in my purse, and nothing particular to interest me
on shore, I thought I would sail about a little and see the watery part
of the world. It is a way I have of driving off the spleen, and regulating
the circulation. - Moby Dick''' words = [[x for x in line.split() if len(x)>3] for line in text.split('\n')] print(words)</pre>
<p>This is a nested list comprehension statement. This creates a new inner list as an element of the outer list. Each inner list contains all words with more than 4 characters. Each outer list contains an inner list for each line of text. </p>
<h2>Where to Go From Here?</h2>
<p>Want to increase your Python skill on a daily basis? Just by following a series of FREE Python course emails? Then join the #1 <a href="https://blog.finxter.com/subscribe/">Python Email Academy in the world! </a></p>
<p>For my subscribers, I regularly publish educative emails about the most important Python topics. Register and join my community of thousands of ambitious coders. I guarantee, you will love it! </p>
<p>(Besides—it’s free and you can unsubscribe anytime so you’ve nothing to lose and everything to gain.)</p>
<p>join the #1 <a href="https://blog.finxter.com/subscribe/">Python Email Academy in the world!</a></p>
</div>


https://www.sickgaming.net/blog/2020/04/...in-python/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016