Notice how the authors’ names are in lowercase in the above list. We would now like to format them in the title case and store them in a new list called author_list.
Note: In Python, the string method title() accepts a string as an argument, and returns a copy of the string formatted in the title case. That is, the first letter of each word is capitalized: First-name Last-name
So here’s all you need to do:
loop through the authors list and for each author in the list,
call author.title() to get a title-cased copy of the string.
In the above output, observe how the names of all the authors have been formatted in the title case—which is what we wanted.
Using List Comprehension with Multiple Lists
So far, you’ve learned how to use list comprehension to create new lists from one existing list. Now let’s learn how to create a new list from multiple lists.
For example, consider this problem: You have two lists l_arr and b_arr containing the lengths and breadths of 4 rectangles.
And you need to create a new list area that includes the area of these 4 rectangles. Remember, area = length * breadth.
l_arr = [4,5,1,3]
b_arr = [2,1,7,9]
You’ll need elements from both the lists (l_arr and b_arr) in order to calculate the area. And you can do it using Python’s zip() function.
Note: In Python, the zip() function takes in one or more iterables as arguments with the syntax zip(*iterables). It then returns an iterator of tuples, where the tuple i contains the element i from each of the iterables.
The following image describes this in detail. You have 4 values in l_arr and b_arr, so the range of indices is from 0 to 3. As you can see, the tuple 0 contains l_arr and b_arr, tuple 1 contains l_arr and b_arr, and so on.
Therefore, you can loop through zip(l_arr,b_arr) as shown below:
area = [l*b for l,b in zip(l_arr,b_arr)]
In the next section, you’ll learn how to use conditional statements inside a list comprehension.
Python List Comprehension with Condition Syntax
Let’s start by building on the previous syntax for list comprehension.
Here’s the syntax:
<new_list> = [<expression> for <item> in <iterable> if <condition>]
Instead of computing the <expression> for all items, you’d only like to do it for those items that satisfy a specific <condition>—where, condition := True. And this leads to a simplified syntax as shown:
▶ With that, let’s proceed to code examples.
Python List Comprehension with Condition Examples
#1. You’re given the string “I’m learning Python in 2022”. You’d like to get a list of all digits in this string. So how do you do it?
In Python, <char>.isdigit() acts on a character <char> and returns True if it’s a digit (0-9); else it returns False.
The code snippet below shows how you can collect the list of all digits in the string str1.
str1 = "I'm learning Python3 in 2022"
digits = [char for char in str1 if char.isdigit()]
['3', '2', '0', '2', '2']
In the above code:
you loop through the string str1,
access each char to check if it’s a digit using the isdigit() method, and
add char to the new list digits only if it is a digit.
Let’s take another example.
#2.You have a list of fruits.🍊 And you’d like to create a list starts_with_b that contains all fruits from the fruits list that start with b. You can use the startswith() method to write the condition.
The <str>.startswith('char') returns True if <str> starts with ‘char’; else it returns False.
fruits = ['blueberry','apple','banana','orange','cherry']
starts_with_b = [fruit for fruit in fruits if fruit.startswith('b')]
In the output above, we get 'blueberry' and 'banana' which are the two fruits that start with 'b' in the fruits list, as we expected.
And that wraps up our discussion on list comprehension.
I hope this tutorial helped you understand list comprehensions in Python.
You can use [<do this> for <all-items> in <this-list>] to create a new list using list comprehension.
Additionally, you can use the syntax [<do this> for <all-items> in <this-list> if <condition-is-True>] with the if conditional statement.
Additionally, you’ve also coded several examples. As a next step, you can try rewriting some of your existing Python loops for list creation using list comprehension. Happy coding! Until the next tutorial.😄
Google Knowledge Panel are the boxes that appear on Google when you search for specific entities such as people, organizations, or places. They are meant to give you a quick understanding through boxes about the information you are looking for.
Statistical analysis provides a systematic and objective approach to extracting meaningful insights from data. It helps in making evidence-based decisions, drawing reliable conclusions, and understanding the inherent variability and uncertainties in various processes and systems.