avatarBetter Everything

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

2781

Abstract

y using <code>3n</code>: <code>[3n for n in numbers]</code></li></ol><p id="4842">Step by step each number in the <code>numbers</code> list is taken, a transformation (in this case a calculation) is performed on it and the result gets added to the new list. It works just like our <code>for</code> loop example, but in one line.</p><h2 id="3f49">Filtering lists</h2><p id="4b5d">If we have the same list of numbers <code>numbers = [10,120,50,70,240,20,190]</code> we could use a <code>for</code> loop to filter the list. Filtering a list means taking only certain items of it based on a condition.</p><p id="163d">Let’s make a list of numbers that are bigger than 100 out of the <code>numbers</code> list.</p><div id="9647"><pre>big_numbers = [] <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> numbers: <span class="hljs-keyword">if</span> number><span class="hljs-number">100</span>: big_numbers.append(number)</pre></div><h2 id="0872">Using a list comprehension to filter a list</h2><p id="39be">A list comprehension can also be used to filter a list. Here is 1 line of code to do the same as the 4 lines of code above.</p><div id="0ee2"><pre>big_numbers = [n <span class="hljs-keyword">for</span> n <span class="hljs-keyword">in</span> numbers <span class="hljs-keyword">if</span> n><span class="hljs-number">100</span>]</pre></div><p id="105e">The formula of a list comprehension that filters is:</p><ol><li>Use the square brackets at the start and end: <code>[]</code></li><li>Define over what iterable you want to loop. In our case we want to loop over each number <code>n</code> in the list <code>numbers</code>: <code>[for n in numbers]</code></li><li>Specify the condition that needs to be met for a variable to be put in our new list: <code>[for n in numbers if n>100]</code></li><li>Specify what you want to put in the new list, in our case just <code>n</code>. But we could also put a transformation on <code>n</code>, for example triple it with <code>3*n</code>: <code>[n for n in numbers if n>100]</code></li></ol><p id="f339">Step-by-step each item of the <code>numbers</code> list is taken, we check if a condition is met and if so we put it in our new list.</p><h2 id="b955">Other types of comprehensions</h2><p id="47b6">To illustrate the possibilities of using comprehensions here are some examples:</p><p id="a091"><b>From string to list </b>Result: <code>['a', 'b', 'c', 'd', 'e']</code></p><div id="26fe"><pre>text = <span class="hljs-string">'abcde'</span> letters = [l <span class="hljs-keyword">for</span> l <span class="hljs-keyword">in</span> text] <span class="hljs-built_in">print</span>(letters)</pre></div><p id="bbef"><b>From list to string including a transformation </b>Result: <code>Hell

Options

o</code></p><div id="f351"><pre>numbers = [<span class="hljs-number">72</span>,<span class="hljs-number">101</span>,<span class="hljs-number">108</span>,<span class="hljs-number">108</span>,<span class="hljs-number">111</span>] text = <span class="hljs-string">''</span>.join(<span class="hljs-built_in">chr</span>(n) <span class="hljs-keyword">for</span> n <span class="hljs-keyword">in</span> numbers) <span class="hljs-built_in">print</span>(text)</pre></div><p id="1f7f"><b>From tuple of tuples to dictionary including a filter </b>Result: <code>{'USA': 8133, 'Germany': 3359, 'Italy': 2452, 'France': 2436}</code></p><div id="1553"><pre>gold_reserves = (('USA',<span class="hljs-number">8133</span>),('Germany',<span class="hljs-number">3359</span>),('Italy',<span class="hljs-number">2452</span>), ('France',<span class="hljs-number">2436</span>),('Russia',<span class="hljs-number">2299</span>))

gold_reserves2 = {ctry:gold <span class="hljs-keyword">for</span> ctry,gold <span class="hljs-keyword">in</span> gold_reserves <span class="hljs-keyword">if</span> gold>2300} <span class="hljs-built_in">print</span>(gold_reserves2)</pre></div><h1 id="a418">Thank you for reading!</h1><p id="8ee0">You can <b>get full access to all my posts by joining Medium</b>. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium:</p><div id="80fc" class="link-block"> <a href="https://medium.com/@BetterEverything/membership"> <div> <div> <h2>Join Medium with my referral link — Better Everything</h2> <div><h3>Read every story from Better Everything (and thousands of other writers on Medium). Your membership fee directly…</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*aa4Y_6MHVoY6Wl-9)"></div> </div> </div> </a> </div><p id="ba8f">You might also like:</p><div id="0441" class="link-block"> <a href="https://readmedium.com/python-one-liner-if-else-statements-e47a715854da"> <div> <div> <h2>Python one-liner if-else statements</h2> <div><h3>Conditonal expressions or ternary operators are Python one liners to work with conditions, like an if-else statement…</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*ZYBgREjWshfQznup.jpeg)"></div> </div> </div> </a> </div></article></body>

Python one-liner to transform and filter lists

In this article I want to introduce list comprehensions. With a list comprehension you can make a new list by looping over an existing list or other iterable like tuple, string, dictionary or set.

By using a list comprehension you can create a new list by looping over an existing list or other iterable in one line. Image by catalyststuff on Freepik

List transformations

Suppose we have a Python list: numbers = [10,120,50,70,240,20,190].

If we needed to make a new list in which each item would be tripled: numbers_tripled = [30,360,150,210,720,60,570], we could use a for loop.

We would start with making a new empty list numbers_tripled = []. And then loop over the orignal numbers list to append each tripled number to the new list.

numbers = [10,120,50,70,240,20,190]

numbers_tripled = []
for number in numbers:
    numbers_tripled.append(3 * number)

Using a list comprehension to transform a list

By using a list comprehension we can do the same as in the above example but we will only need one line:

numbers = [10,120,50,70,240,20,190]

numbers_tripled = [3*n for n in numbers]

The formula to make a list comprehension is:

  1. Use the square brackets at the start and end: []
  2. Define over what iterable you want to loop. In our case we want to loop over each number n in the list numbers: [for n in numbers]
  3. Use the iterable’s items to make the transformation. In our case the list’s items are called n. We will triple each n by using 3*n: [3*n for n in numbers]

Step by step each number in the numbers list is taken, a transformation (in this case a calculation) is performed on it and the result gets added to the new list. It works just like our for loop example, but in one line.

Filtering lists

If we have the same list of numbers numbers = [10,120,50,70,240,20,190] we could use a for loop to filter the list. Filtering a list means taking only certain items of it based on a condition.

Let’s make a list of numbers that are bigger than 100 out of the numbers list.

big_numbers = []
for number in numbers:
    if number>100:
        big_numbers.append(number)

Using a list comprehension to filter a list

A list comprehension can also be used to filter a list. Here is 1 line of code to do the same as the 4 lines of code above.

big_numbers = [n for n in numbers if n>100]

The formula of a list comprehension that filters is:

  1. Use the square brackets at the start and end: []
  2. Define over what iterable you want to loop. In our case we want to loop over each number n in the list numbers: [for n in numbers]
  3. Specify the condition that needs to be met for a variable to be put in our new list: [for n in numbers if n>100]
  4. Specify what you want to put in the new list, in our case just n. But we could also put a transformation on n, for example triple it with 3*n: [n for n in numbers if n>100]

Step-by-step each item of the numbers list is taken, we check if a condition is met and if so we put it in our new list.

Other types of comprehensions

To illustrate the possibilities of using comprehensions here are some examples:

From string to list Result: ['a', 'b', 'c', 'd', 'e']

text = 'abcde'
letters = [l for l in text]
print(letters)

From list to string including a transformation Result: Hello

numbers = [72,101,108,108,111]
text = ''.join(chr(n) for n in numbers)
print(text)

From tuple of tuples to dictionary including a filter Result: {'USA': 8133, 'Germany': 3359, 'Italy': 2452, 'France': 2436}

gold_reserves = (('USA',8133),('Germany',3359),('Italy',2452),
                 ('France',2436),('Russia',2299))

gold_reserves2 = {ctry:gold for ctry,gold in gold_reserves if gold>2300}
print(gold_reserves2)

Thank you for reading!

You can get full access to all my posts by joining Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium:

You might also like:

Python
Python Tips
Best Practices
Software Development
Programming
Recommended from ReadMedium