Chuyển tới nội dung
Home » Set Comprehension In Python | Deciding When Not To Use A List Comprehension

Set Comprehension In Python | Deciding When Not To Use A List Comprehension

Python Tutorial: Comprehensions - How they work and why you should be using them

In python programming, we use different data structures like lists, tuples, sets, and dictionaries. Often we create new lists, sets or dictionaries from existing objects in our programs. In this article, we will study set comprehension and see how it is used in python to create new sets from existing objects in Python. We will also look at some examples of set comprehension in Python.

How to use a for loop to create a list in Python

One way to create a list in Python is by using a

for

loop.

For example, you can use the

range()

function to create a list of numbers ranging from 0 – 4.


#first create an empty list my_list = [] #iterate over the numbers 0 - 4 using the range() function #range(5) creates an iterable, starting from 0 up to (but not including) 5 #Use the .append() method to add the numbers 0 - 4 to my_list for num in range(5): my_list.append(num) #print my_list print(my_list) #output #[0, 1, 2, 3, 4]

What if you already have a list of numbers, but want to create a new list with their squares?

You could again use a

for

loop, like so:


#initial list of numbers numbers = [1,2,3,4,5,6] #create a new,empty list to hold their squares square_numbers = [] #iterate over initial list #multiply each number by itself #use .append() method, to add the square to the new list, square_numbers for num in numbers: square_numbers.append(num * num) #print new list print(square_numbers) #output #[1, 4, 9, 16, 25, 36]

But there is a quicker and more succinct way to achieve the same results – by using list comprehension.

Benefits of List Comprehension

List comprehension is one of the most remarkable features of Python that enables writing clear and concise codes. Some of its significant benefits are:

  • Facilitates writing the code in fewer lines
  • Allows writing codes that are easier to understand and that adhere to Python guidelines
  • Converts iterable (list) into a formula
  • Filters and maps the items in a list to boost code performance

When to Use List Comprehension

You can use list comprehension in Python to repeat a code multiple times or to modify or filter the items in a list. Therefore, you can use list comprehension as an alternative to loop or lambda in Python to transform items in an existing list.

Python Tutorial: Comprehensions - How they work and why you should be using them
Python Tutorial: Comprehensions – How they work and why you should be using them

Python3


state


'Gujarat'


'Maharashtra'


'Rajasthan'


capital


'Gandhinagar'


'Mumbai'


'Jaipur'


dict_using_comp


{key:value


for


(key, value)


in


zip


(state, capital)}


print


"Output Dictionary using dictionary comprehensions:"


dict_using_comp)

Output:

Output Dictionary using dictionary comprehensions: {‘Rajasthan’: ‘Jaipur’, ‘Maharashtra’: ‘Mumbai’, ‘Gujarat’: ‘Gandhinagar’}

Summary

  • Use Python set comprehension to create a new set based on an existing set by applying an expression to each element of the existing set.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Understanding Python List Comprehensions

One of Python’s most distinctive features is the list comprehension, which you can use to create powerful functionality within a single line of code. However, many developers struggle to fully leverage the more advanced features of list comprehensions in Python. Some programmers even use them too much, which can lead to code that’s less efficient and harder to read.

By the end of this tutorial, you’ll understand the full power of Python list comprehensions and know how to use their features comfortably. You’ll also gain an understanding of the trade-offs that come with using them so that you can determine when other approaches are preferable.

In this tutorial, you’ll learn how to:

  • Rewrite loops and

    map()

    calls as list comprehensions in Python
  • Choose between comprehensions, loops, and

    map()

    calls
  • Supercharge your comprehensions with conditional logic
  • Use comprehensions to replace

    filter()
  • Profile your code to resolve performance questions

Get Your Code: Click here to download the free code that shows you how and when to use list comprehensions in Python.

22. List Set Dict Comprehensions [Python 3 Programming Tutorials]
22. List Set Dict Comprehensions [Python 3 Programming Tutorials]

What is list comprehension in Python? A syntax overview

When you’re analyzing and working with lists in Python, you’ll often have to manipulate, modify, or perform calculations on every single item in the list, all at once.

You may also need to create new lists from scratch, or create a new list based on the values of an already existing list.

List comprehension is a fast, short, and elegant way to create lists compared to other iterative methods, like

for

loops.

The general syntax for list comprehension looks like this:


new_list = [expression for variable in iterable]

Let’s break it down:

  • List comprehensions start and end with opening and closing square brackets,

    []

    .
  • Then comes the

    expression

    or operation you’d like to perform and carry out on each value inside the current iterable. The results of these calculations enter the new list.
  • The

    expression

    is followed by a

    for

    clause.

  • variable

    is a temporary name you want to use for each item in the current list that is going through the iteration.
  • The

    in

    keyword is used to loop over the iterable.

  • iterable

    can be any Python object, such as a list, tuple, string and so on.
  • From the iteration that was performed and the calculations that took place on each item during the iteration, new values were created which are saved to a variable, in this case

    new_list

    . The old list (or other object) will remain unchanged.
  • There can be an optional

    if

    statement and additional

    for

    clause.

Python3


output_list


[]


for


var


in


range


10


):


output_list.append(var


print


"Output List using for loop:"


, output_list)

Output:

Output List using for loop: [1, 4, 9, 16, 25, 36, 49, 64, 81]

Example 2: Squaring Number using List comprehensions

In This we use list comprehension to generate a new list. It iterates through the numbers in the range from 1 to 9 (inclusive). For each number

var

, it calculates the square of the number using the expression and adds the result to the new list. The printed output will contain the squares of numbers from 1 to 9.

Python dictionary comprehension 🕮
Python dictionary comprehension 🕮

Python3


input_list


dict_using_comp


{var:var


for


var


in


input_list


if


var


print


"Output Dictionary using dictionary comprehensions:"


,dict_using_comp)

Output:

Output Dictionary using dictionary comprehensions: {1: 1, 3: 27, 5: 125, 7: 343}

Example 1: Mapping states with their capitals without Using dictionary comprehension

Given two lists containing the names of states and their corresponding capitals, construct a dictionary which maps the states with their respective capitals. Let’s see how to do this using for loops and dictionary comprehension.

Generator Comprehensions

Generator Comprehensions are very similar to list comprehensions. One difference between them is that generator comprehensions use circular brackets whereas list comprehensions use square brackets. The major difference between them is that generators don’t allocate memory for the whole list. Instead, they generate each value one by one which is why they are memory efficient. Let’s look at the following example to understand generator comprehension:

List Comprehension in Python
List Comprehension in Python

Supercharging Your Python List Comprehensions

One benefit of using a list comprehension in Python is that it’s a single tool that you can use in many different situations. In addition to standard list creation, list comprehensions can also be used for mapping and filtering. In this section, you’ll find advanced techniques to work with list comprehensions in Python.

Filter Values From a List

The most common way to add conditional logic to a list comprehension is to add a conditional to the end of the expression.

Earlier, you saw this formula for how to create list comprehensions:


new_list = [expression for member in iterable]

While this formula is accurate, it’s also a bit incomplete. A more complete description of the comprehension formula adds support for optional conditionals.

Here, your conditional statement comes just before the closing bracket:


new_list = [expression for member in iterable if conditional]

Conditionals are important because they allow list comprehensions to filter out unwanted values, which would normally require a call to

filter()

:


>>> sentence = "the rocket came back from mars" >>> [char for char in sentence if char in "aeiou"] ['e', 'o', 'e', 'a', 'e', 'a', 'o', 'a']

In this code block, the conditional statement filters out any characters in

sentence

that aren’t vowels.

The conditional can test any valid expression. If you need a more complex filter, then you can even move the conditional logic to a separate function:


>>> sentence = ( ... "The rocket, who was named Ted, came back " ... "from Mars because he missed his friends." ... ) >>> def is_consonant(letter): ... vowels = "aeiou" ... return letter.isalpha() and letter.lower() not in vowels ... >>> [char for char in sentence if is_consonant(char)] ['T', 'h', 'r', 'c', 'k', 't', 'w', 'h', 'w', 's', 'n', 'm', 'd', 'T', 'd', 'c', 'm', 'b', 'c', 'k', 'f', 'r', 'm', 'M', 'r', 's', 'b', 'c', 's', 'h', 'm', 's', 's', 'd', 'h', 's', 'f', 'r', 'n', 'd', 's']

Here, you create a complex filter,

is_consonant()

, and pass this function as the conditional statement for your list comprehension. Note that you also pass the member value

char

as an argument to your function.

You can place the conditional at the end of the statement for basic filtering, but what if you want to change a member value instead of filtering it out? In this case, it’s useful to place the conditional near the beginning of the expression. You can do so by taking advantage of the conditional expression:


new_list = [true_expr if conditional else false_expr for member in iterable]

By placing the conditional logic at the beginning of a list comprehension, you can use conditional logic to select from multiple possible output options. For example, if you have a list of prices, then you may want to replace negative prices with and leave the positive values unchanged:


>>> original_prices = [1.25, -9.45, 10.22, 3.78, -5.92, 1.16] >>> [price if price > 0 else 0 for price in original_prices] [1.25, 0, 10.22, 3.78, 0, 1.16]

Here, your expression is a conditional expression,

price if price > 0 else 0

. This tells Python to output the value of

price

if the number is positive, but to use if the number is negative. If this seems overwhelming, then it may be helpful to view the conditional logic as its own function:


>>> def get_price(price): ... return price if price > 0 else 0 ... >>> [get_price(price) for price in original_prices] [1.25, 0, 10.22, 3.78, 0, 1.16]

Now, your conditional expression is contained within

get_price()

, and you can use it as part of your list comprehension.

Remove Duplicates With Set and Dictionary Comprehensions

While the list comprehension in Python is a common tool, you can also create set and dictionary comprehensions. A set comprehension is almost exactly the same as a list comprehension in Python. The difference is that set comprehensions make sure the output contains no duplicates. You can create a set comprehension by using curly braces instead of brackets:


>>> quote = "life, uh, finds a way" >>> {char for char in quote if char in "aeiou"} {'a', 'e', 'u', 'i'}

Your set comprehension outputs all the unique vowels that it found in

quote

. Unlike lists, sets don’t guarantee that items will be saved in any particular order. This is why the first member of the set is , even though the first vowel in

quote

is .

Dictionary comprehensions are similar, with the additional requirement of defining a key:


>>> {number: number * number for number in range(10)} {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

To create the dictionary, you use curly braces (

{}

) as well as a key-value pair (

number: number * number

) in your expression.

Assign Values With the Walrus Operator

Python 3.8 introduced the assignment expression, also known as the walrus operator. To understand how you can use it, consider the following example.

Say you need to make ten requests to an API that will return temperature data. You only want to return results that are greater than 100 degrees Fahrenheit. Assume that each request will return different data. In this case, the formula

expression for member in iterable if conditional

provides no way for the conditional to assign data to a variable that the expression can access.

You need the temperature in both the expression and the conditional so this is a challenge. The walrus operator (

:=

) solves this problem. It allows you to run an expression while simultaneously assigning the output value to a variable. The following example shows how this is possible, using

get_weather_data()

to generate fake weather data:


>>> import random >>> def get_weather_data(): ... return random.randrange(90, 110) ... >>> [temp for _ in range(20) if (temp := get_weather_data()) >= 100] [107, 102, 109, 104, 107, 109, 108, 101, 104]

Note that the walrus operator needs to be in the conditional part of your comprehension. You won’t often need to use the assignment expression inside of a list comprehension in Python, but it’s a useful tool to have at your disposal when necessary.

Dictionary Comprehensions

Extending the idea of list comprehensions, we can also create a dictionary using dictionary comprehensions. The basic structure of a dictionary comprehension looks like below.

output_dict = {key:value for (key, value) in iterable if (key, value satisfy this condition)}

Example 1: Generating odd number with their cube values without using dictionary comprehension

Suppose we want to create an output dictionary which contains only the odd numbers that are present in the input list as keys and their cubes as values. Let’s see how to do this using for loops and dictionary comprehension.

Python Set Comprehension -- A Simple Formula Guide
Python Set Comprehension — A Simple Formula Guide

Conclusion

And there you have it! You now know the basics of list comprehension in Python.

It offers an elegant and concise syntax for creating new lists based on existing lists or other iterables.

If you’re interested in learning more about Python, freeCodeCamp has a Python Certification.

In this project-based curriculum, you’ll start with learning programming fundamentals and advance to more complex subjects such as data structutes. You’ll also build five projects to put to practice what you’ve learned.

Thanks for reading and happy coding!

Set comprehension is a concise way to create a new set based on existing iterable(s). It is similar to a but returns a set instead of a list. In this article, we will discuss Set comprehension and how to create sets by using different data structures in Python.

Python Sets in python is a one-dimensional data structure that will not allow duplicates. Set comprehension is also a data structure that will store the data by filtering the elements using conditions/expressions. So the set comprehension will take an iterator to iterate the elements from other data structures using an expression/condition.

Create Set from Tuple using Set Comprehension

Here, let’s create a set from the tuple using the set comprehension.


# Consider 8 strings in a tuple tuple1 = ("wecome","to","sparkby","examples","wecome","to","sparkby","examples") print("Tuple : ",tuple1) # Create set from the tuple converted = {i for i in tuple1} print("Set: ",converted) # Output: # Tuple : ('wecome', 'to', 'sparkby', 'examples', 'wecome', 'to', 'sparkby', 'examples') # Set: {'to', 'sparkby', 'examples', 'wecome'}

First we created a tuple that hold 8 strings with duplicates, Now we are passing each element one by one in the tuple to the Set using the set comprehension. As we know that Set will not allow duplicates, there ate 4 duplicates in the tuple, so set won’t included them. Hence the set holds only 4 elements.

Dictionary Comprehension - Create Complex Data Structures Step by Step
Dictionary Comprehension – Create Complex Data Structures Step by Step

List Comprehensions

List Comprehensions provide an elegant way to create new lists. The following is the basic structure of list comprehension:

Syntax: output_list = [output_exp for var in input_list if (var satisfies this condition)]

Note that list comprehension may or may not contain an if condition. List comprehensions can contain multiple

Example 1: Generating an Even list WITHOUT using List comprehensions

Suppose we want to create an output list that contains only the even numbers which are present in the input list. Let’s see how to do this using loops, list comprehension, and list comprehension, and decide which method suits you better.

Python3


state


'Gujarat'


'Maharashtra'


'Rajasthan'


capital


'Gandhinagar'


'Mumbai'


'Jaipur'


output_dict


{}


for


(key, value)


in


zip


(state, capital):


output_dict[key]


value


print


"Output Dictionary using for loop:"


,output_dict)

Output:

Output Dictionary using for loop: {‘Gujarat’: ‘Gandhinagar’, ‘Maharashtra’: ‘Mumbai’, ‘Rajasthan’: ‘Jaipur’}

Example 2: Mapping states with their capitals with using dictionary comprehension

Here we will use dictionary comprehension to initializes two lists,

state

and

capital

, containing corresponding pairs of states and their capitals. It iterates through the pairs of

state

and

capital

using the

zip()

function, and for each pair, it creates a key-value pair in the dictionary. The key is taken from the

state

list, and the value is taken from the

capital

list. Finally, the printed output will contain the mapping of states to their capitals.

Python List Comprehensions Made Easy!!
Python List Comprehensions Made Easy!!

Transforming Lists in Python

There are a few different ways to create and add items to a lists in Python. In this section, you’ll explore

for

loops and the

map()

function to perform these tasks. Then, you’ll move on to learn about how to use list comprehensions and when list comprehensions can benefit your Python program.

Use for Loops

The most common type of loop is the

for

loop. You can use a

for

loop to create a list of elements in three steps:

  1. Instantiate an empty list.
  2. Loop over an iterable or range of elements.
  3. Append each element to the end of the list.

If you want to create a list containing the first ten perfect squares, then you can complete these steps in three lines of code:


>>> squares = [] >>> for number in range(10): ... squares.append(number * number) ... >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Here, you instantiate an empty list,

squares

. Then, you use a

for

loop to iterate over

range(10)

. Finally, you multiply each number by itself and append the result to the end of the list.

Work With map Objects

For an alternative approach that’s based in functional programming, you can use

map()

. You pass in a function and an iterable, and

map()

will create an object. This object contains the result that you’d get from running each iterable element through the supplied function.

As an example, consider a situation in which you need to calculate the price after tax for a list of transactions:


>>> prices = [1.09, 23.56, 57.84, 4.56, 6.78] >>> TAX_RATE = .08 >>> def get_price_with_tax(price): ... return price * (1 + TAX_RATE) ... >>> final_prices = map(get_price_with_tax, prices) >>> final_prices

>>> list(final_prices) [1.1772000000000002, 25.4448, 62.467200000000005, 4.9248, 7.322400000000001]

Here, you have an iterable,

prices

, and a function,

get_price_with_tax()

. You pass both of these arguments to

map()

and store the resulting

map

object in

final_prices

. Finally, you convert

final_prices

into a list using

list()

.

Leverage List Comprehensions

List comprehensions are a third way of making or transforming lists. With this elegant approach, you could rewrite the

for

loop from the first example in just a single line of code:


>>> squares = [number * number for number in range(10)] >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Rather than creating an empty list and adding each element to the end, you simply define the list and its contents at the same time by following this format:


new_list = [expression for member in iterable]

Every list comprehension in Python includes three elements:


  1. expression

    is the member itself, a call to a method, or any other valid expression that returns a value. In the example above, the expression

    number * number

    is the square of the member value.

  2. member

    is the object or value in the list or iterable. In the example above, the member value is

    number

    .

  3. iterable

    is a list, set, sequence, generator, or any other object that can return its elements one at a time. In the example above, the iterable is

    range(10)

    .

Because the expression requirement is so flexible, a list comprehension in Python works well in many places where you would use

map()

. You can rewrite the pricing example with its own list comprehension:


>>> prices = [1.09, 23.56, 57.84, 4.56, 6.78] >>> TAX_RATE = .08 >>> def get_price_with_tax(price): ... return price * (1 + TAX_RATE) ... >>> final_prices = [get_price_with_tax(price) for price in prices] >>> final_prices [1.1772000000000002, 25.4448, 62.467200000000005, 4.9248, 7.322400000000001]

The only distinction between this implementation and

map()

is that the list comprehension in Python returns a list, not a map object.

Tips on Using List Comprehension

Using list comprehension in Python is a difficult task, especially for beginners. These tips on using list comprehension in Python will

Use Conditional Logic

If-else statements, also called conditional statements in programming, add logic to a code that can be executed only when certain conditions are met. Using conditional logic in list comprehension gives you more accurate results and allows you to modify a list or filter unnecessary items.

Use Set and Dictionary Comprehension

Dictionary in Python is a data type that stores data in the form of key-value pairs. For instance, apple:red, and mango:yellow. Here, apple and mango are the keys, and red and yellow are the values. Set is a data type that comprises elements in an abstract manner and has no duplicate items. You can use set and dictionary comprehension to modify list comprehensions.

Use the Walrus Operator

The Walrus operator is an expression that assigns value to a variable in Python. You can use the Walrus operator with list comprehension to avoid calling the same function numerous times.

Python lists, sets, and tuples explained 🍍
Python lists, sets, and tuples explained 🍍

Python3


input_list


output_gen


(var


for


var


in


input_list


if


var


print


"Output values using generator comprehensions:"


, end


' '


for


var


in


output_gen:


print


(var, end


' '

Output:

Output values using generator comprehensions: 2 4 4 6

Don’t miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.

Dive into the future of technology – explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.

Last Updated :
18 Aug, 2023

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

Overview:

Set comprehension could be a way to form a new set from an iterable object, such as a list or a tuple. It can assist you in writing more expressive code 💻 and spare time 🕐. In this lesson, we’ll jump deeper into set comprehension, covering its syntax 💬, how to utilize it, and a few best practices to take after 📜.

What is Set Comprehension?

Set comprehension may be a concise and capable way to make a new set based on an existing iterable object, such as a list, a tuple, or a run. It permits you to write code in a more expressive way 📝📝 and can spare you a lot of time and exertion.

Syntax

Set comprehension has a simple and elegant syntax that consists of two parts:


new_set = {expression for variable in iterable if condition}

The for loop and the if statement are the two fundamental building blocks of set comprehension. The for loop iterates over the iterable object 🔃, and the if statement filters the elements based on a condition.

Let’s see some examples of set comprehension in action.

Creating a new set of squared values


numbers = [1, 2, 3, 4, 5] squared_numbers = {x**2 for x in numbers} print(squared_numbers)

In this example, we’re creating a new set called squared_numbers that contains the squared values of the elements in the numbers list.

Filtering elements in a list


numbers = [1, 2, 3, 4, 5] even_numbers = {x for x in numbers if x % 2 == 0} print(even_numbers)

In this example, we’re creating a new set called even_numbers that contains only the even numbers from the numbers list.

Using a set comprehension with strings


words = ['apple', 'banana', 'cherry'] vowels = {'a', 'e', 'i', 'o', 'u'} vowel_words = {word for word in words if any(letter in vowels for letter in word)} print(vowel_words)

In this example, we’re creating a new set called vowel_words that contains only the words from the words list that contain at least one vowel.

Best Practices

Here are some best practices to follow when using set comprehension in your code:

Conclusion

Set comprehension is a powerful and elegant feature of Python that allows you to create new sets easily. It can help you write more concise and readable code 📝📝, saving you time and effort 🕙. By following best practices 📖📖 and using set comprehension effectively, you can make your Python code more efficient and expressive.

Key Takeaways

Quiz

Answer: a. A way to create a new set based on an existing iterable object

Answer: a. new_set = {expression for variable in iterable if condition}

Answer: d. It filters the elements based on a condition

Answer: b. {x for x in numbers if x % 2 == 0}

Answer: a. Keep it simple, use meaningful variable names, and use curly braces to increase readability

Related Tutorials

view All

Related Articles

view All

8 mins

5442

9 mins

2208

7 mins

4895

Related Tutorials to watch

Top Articles toRead

Read

What is List Comprehension in Python and its Advantages?

The use of computers has evolved over the centuries. They were primarily invented to carry out complex mathematical operations. However, in the last few decades, computers have been used for many advanced purposes, such as artificial intelligence, data analysis, and machine learning. The significant change in computer operations made it necessary to optimize computer memory. It gave birth to the concept of lists in programming languages that allow for the manipulation of symbols and do not restrict the computer’s memory to specific variables. That also created the need for list comprehension, which provides a simple way to create these lists. For anyone interested in coding, it is important to have a clear understanding of the meaning of lists. Let us find out what is list comprehension in Python, its advantages, and its uses.

Conclusion

In this tutorial, you learned how to use a list comprehension in Python to accomplish complex tasks without making your code overly complicated.

Whenever you have to choose a list creation method, try multiple implementations and consider what’s most convenient to read and understand in your specific scenario. If performance is important, then you can use profiling tools to give you actionable data instead of relying on hunches or guesses about what works the best.

Now you can:

  • Simplify loops and

    map()

    calls with declarative list comprehensions
  • Supercharge your comprehensions with conditional logic
  • Create set and dictionary comprehensions
  • Determine when code clarity or performance dictates an alternative approach

Remember that while Python list comprehensions get a lot of attention, your intuition and ability to use data when it counts will help you write clean code that serves the task at hand. This, ultimately, is the key to making your code Pythonic!

Get Your Code: Click here to download the free code that shows you how and when to use list comprehensions in Python.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Understanding Python List Comprehensions

Lộ trình lấy gốc Ngữ Pháp Tiếng Anh chi tiết | Tự Học Siêu Tiết Kiệm | Nói Tiếng Anh Lưu Loát
Lộ trình lấy gốc Ngữ Pháp Tiếng Anh chi tiết | Tự Học Siêu Tiết Kiệm | Nói Tiếng Anh Lưu Loát

Set Comprehensions

Set comprehensions are pretty similar to list comprehensions. The only difference between them is that set comprehensions use curly brackets

{ }

Let’s look at the following example to understand set comprehensions.

Example 1 : Checking Even number Without using set comprehension

Suppose we want to create an output set which contains only the even numbers that are present in the input list. Note that set will discard all the duplicate values. Let’s see how we can do this using for loops and set comprehension.

How to use list comprehension in Python

Using the same example from earlier on, here is how you’d create a new list of numbers from 0 – 4 with the

range()

function in just one single line, using list comprehension:


new_list = [num for num in range(5)] print(new_list) #output #[0, 1, 2, 3, 4]

This has the same output as the

for

loop example, but with significantly less code!

Let’s break it down:

  • the iterable in this case is a sequence of numbers from 0 to 4, using

    range(5)

    .

    range()

    constructs a list of numbers.
  • You use the

    in

    keyword to iterate over the numbers.
  • The

    num

    following the

    for

    clause is a variable, a temporary name for each value in the iterable. So

    num

    would be equal toin the first iteration, then

    num

    would be equal toin the next iteration and so on, until it reached and equalled the number 4, where the iteration would stop.
  • The

    num

    before the

    for

    clause is an expression for each item in the sequence.
  • Finally, the new list (or other iterable) that is created gets stored in the variable

    new_list

    .

You can even perform mathematical operations on the items contained in the iterable and the result will be added to the new list:


new_list = [num * 2 for num in range(5)] print(new_list) #output #[0, 2, 4, 6, 8]

Here each number in

range(5)

will be multiplied by two and the new value will be stored in the variable

new_list

.

What if you had a pre-existing list where you wanted to manipulate and modify each item in it? This would be similar to the example from earlier on, where we created a list of squares.

Again, you can achieve that with just one line of code, using list comprehension:


#initial list numbers = [1,2,3,4,5,6] #new list #num * num is the operation that takes place to create the squares square_numbers = [num * num for num in numbers] print(square_numbers) #output [1, 4, 9, 16, 25, 36]

How to use conditionals with list comprehension in Python

Optionally, you can use an

if

statement with a list comprehension.

The general syntax looks like this:


new_list = [expression for variable in iterable if condition == True]

Conditionals act as a filter and add an extra check for additional precision and customisation when creating a new list.

This means that the value in the expression has to meet certain criteria and a certain condition you speficy, in order to go in the new list.


new_list = [num for num in range(50) if num % 2 == 0] print(new_list) #output #[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48]

In the example above, only the values where the condition

num % 2 == 0

is checked and evaluates to True will enter

new_list

.

The modulo operator is used on every single one of the numbers in the sequence of numbers starting from 0 and ending in 49.

If the remainder of the numbers when divided by 2 is 0, then and only then does it enter the list.

So in this case, it creates a list of only even numbers.

You can then make it as specific as you want.

For example, you could add more than one condition, like so:


new_list = [num for num in range(50) if num > 20 and num % 2 == 0] print(new_list) #output #[22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48]

In this example, there are two conditions

num > 20

and

num % 2 == 0

.

The

and

operator indicates that both have to be met in order for the value to be added to the new list.

The values that don’t meet the conditions are excluded and are not added.

How to use list comprehension on strings in Python

You can create a new list with the individual characters contained in a given string.


fave_language_chars = [letter for letter in "Python"] print(fave_language_chars) #output #['P', 'y', 't', 'h', 'o', 'n']

The new list that gets created is comprised of all the separate letters contained in the string “Python”, which acts as an iterable.

Just like numbers, you can perform operations on the characters contained in a string and customize them depending on how you want them to be in the new list you create.

If you wanted all letters to be uppercase, you would do the following:


fave_language_chars_upper = [letter.upper() for letter in "Python"] print(fave_language_chars_upper) #output #['P', 'Y', 'T', 'H', 'O', 'N']

Here you use the

.upper()

method to convert every single letter in “Python” to uppercase and add them to the

fave_language_chars_upper

variable.

The same goes if you wanted all your letters to be lowercase – you’d instead use the

lower()

method.

Functions in Python are easy 📞
Functions in Python are easy 📞

Python3


input_list


output_set


set


()


for


var


in


input_list:


if


var


output_set.add(var)


print


"Output Set using for loop:"


, output_set)

Output:

Output Set using for loop: {2, 4, 6}

Example 2: Checking Even number using set comprehension

We will use set comprehension to initializes a list with integer values. The code then creates a new set using set comprehension. It iterates through the elements of the

input_list

, and for each element, it checks whether it’s even. If the condition is met, the element is added to the set. The printed output which will contain unique even numbers from the

list.

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Overview:

Set comprehension could be a way to form a new set from an iterable object, such as a list or a tuple. It can assist you in writing more expressive code 💻 and spare time 🕐. In this lesson, we’ll jump deeper into set comprehension, covering its syntax 💬, how to utilize it, and a few best practices to take after 📜.

What is Set Comprehension?

Set comprehension may be a concise and capable way to make a new set based on an existing iterable object, such as a list, a tuple, or a run. It permits you to write code in a more expressive way 📝📝 and can spare you a lot of time and exertion.

Syntax

Set comprehension has a simple and elegant syntax that consists of two parts:


new_set = {expression for variable in iterable if condition}

The for loop and the if statement are the two fundamental building blocks of set comprehension. The for loop iterates over the iterable object 🔃, and the if statement filters the elements based on a condition.

Let’s see some examples of set comprehension in action.

Creating a new set of squared values


numbers = [1, 2, 3, 4, 5] squared_numbers = {x**2 for x in numbers} print(squared_numbers)

In this example, we’re creating a new set called squared_numbers that contains the squared values of the elements in the numbers list.

Filtering elements in a list


numbers = [1, 2, 3, 4, 5] even_numbers = {x for x in numbers if x % 2 == 0} print(even_numbers)

In this example, we’re creating a new set called even_numbers that contains only the even numbers from the numbers list.

Using a set comprehension with strings


words = ['apple', 'banana', 'cherry'] vowels = {'a', 'e', 'i', 'o', 'u'} vowel_words = {word for word in words if any(letter in vowels for letter in word)} print(vowel_words)

In this example, we’re creating a new set called vowel_words that contains only the words from the words list that contain at least one vowel.

Best Practices

Here are some best practices to follow when using set comprehension in your code:

Conclusion

Set comprehension is a powerful and elegant feature of Python that allows you to create new sets easily. It can help you write more concise and readable code 📝📝, saving you time and effort 🕙. By following best practices 📖📖 and using set comprehension effectively, you can make your Python code more efficient and expressive.

Key Takeaways

Quiz

Answer: a. A way to create a new set based on an existing iterable object

Answer: a. new_set = {expression for variable in iterable if condition}

Answer: d. It filters the elements based on a condition

Answer: b. {x for x in numbers if x % 2 == 0}

Answer: a. Keep it simple, use meaningful variable names, and use curly braces to increase readability

Related Tutorials

view All

Related Articles

view All

8 mins

5442

9 mins

2208

7 mins

4895

Related Tutorials to watch

Top Articles toRead

Read

So I have these two problems for a homework assignment and I’m stuck on the second one.

  1. Use a Python Set Comprehension (Python’s equivalent of Set Builder notation) to generate a set of all of the prime numbers that are less than 100. Recall that a prime number is an integer that is greater than 1 and not divisible by any integer other than itself and 1. Store your set of primes in a variable (you will need it for additional parts). Output your set of primes (e.g., with the print function).

  2. Use a Python Set Comprehension to generate a set of ordered pairs (tuples of length 2) consisting of all of the prime pairs consisting of primes less than 100. A Prime Pair is a pair of consecutive odd numbers that are both prime. Store your set of Prime Pairs in a variable. Your set of number 1 will be very helpful. Output your Set of Prime Pairs.

For the first one, this works perfectly:


r= {x for x in range(2, 101) if not any(x % y == 0 for y in range(2, x))}

However, I’m pretty stumped on the second one. I think I may have to take the Cartesian product of the set r with something but I’m just not sure.

This gets me somewhat close but I just want the consecutive pairs.


cart = { (x, y) for x in r for y in r if x < y }

Comprehensions in Python provide us with a short and concise way to construct new sequences (such as lists, sets, dictionaries, etc.) using previously defined sequences. Python supports the following 4 types of comprehension:

  • List Comprehensions
  • Dictionary Comprehensions
  • Set Comprehensions
  • Generator Comprehensions
ALL 11 Dictionary Methods In Python EXPLAINED
ALL 11 Dictionary Methods In Python EXPLAINED

Related Articles

  • How to initialize Set in Python?
  • How to subtract two sets in Python?
  • Python Set clear() Method
  • How to convert Python list to set?
  • Remove set element if exists in Python
  • Find the length of the set in Python
  • How to check two sets are equal in Python?
  • How to convert set to string in Python?
  • Join two or multiple sets in Python
  • How to Append or Add Multiple Values to Set in Python?
  • Python Set pop() method
  • Python Set Comprehension Examples
  • Python Set add() – Add Element to Set

Summary: in this tutorial, you’ll learn how to use Python set comprehension to create a new set based on an existing one.

Examples of set comprehension

Now that we have understood the syntax for set comprehension in python, we will some examples to understand the concept in a better way.

Create a set from elements of another set

If you have to create a set using elements of another set, you can do so by creating a new set. After creating a new set, you can add elements to the new set using add() method and for loop . In the following example, we have created a new set with squares of element of an existing set.


mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} newSet = set() for element in mySet: newSet.add(element**2) print("The existing set is:") print(mySet) print("The Newly Created set is:") print(newSet)

Output:


The existing set is: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} The Newly Created set is: {64, 1, 4, 36, 100, 9, 16, 49, 81, 25}

In the above example, initializing an empty set and then using add() method to add elements to it is inefficient. Instead of this, we can directly initialize the new set with all the elements using the set comprehension as follows.


mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} newSet = {element ** 2 for element in mySet} print("The existing set is:") print(mySet) print("The Newly Created set is:") print(newSet)

Output:


The existing set is: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} The Newly Created set is: {64, 1, 4, 36, 100, 9, 16, 49, 81, 25}

Filter elements from a set based on a condition

We can create a new set from elements of an old set by applying some conditions to the elements. To do this using a for loop, you can use a conditional statement and the add() method as follows. In the following example, we have filtered even numbers from a set.


mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} newSet = set() for element in mySet: if element % 2 == 0: newSet.add(element) print("The existing set is:") print(mySet) print("The Newly Created set is:") print(newSet)

Output:


The existing set is: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} The Newly Created set is: {2, 4, 6, 8, 10}

Instead of the for loop, you can filter out elements from old set to create a new set using set comprehension as follows.


mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} newSet = {element for element in mySet if element % 2 == 0} print("The existing set is:") print(mySet) print("The Newly Created set is:") print(newSet)

Output:


The existing set is: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} The Newly Created set is: {2, 4, 6, 8, 10}

Delete elements from a set

If you have to delete some elements from a set, you can create a new set from the elements that have not to be deleted. After that, you can assign the new set to the old set variable as follows. In the following example, we have deleted all the odd elements from a set.


mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} print("The existing set is:") print(mySet) mySet = {element for element in mySet if element % 2 == 0} print("The modified set is:") print(mySet)

Output:


The existing set is: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} The modified set is: {2, 4, 6, 8, 10}

Change the data type of elements of the set

We can also change the data types of the elements of a set using set comprehension as shown in the following example. Here, we have converted all the integer elements of a set to strings.


mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} newSet = {str(element) for element in mySet } print("The existing set is:") print(mySet) print("The Newly Created set is:") print(newSet)

Output:


The existing set is: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} The Newly Created set is: {'2', '4', '8', '6', '3', '7', '1', '10', '5', '9'}

Best feature of Python | List Comprehensions
Best feature of Python | List Comprehensions

Python3


input_list


list_using_comp


[var


for


var


in


input_list


if


var


print


"Output List using list comprehensions:"


list_using_comp)

Output:

Output List using list comprehensions: [2, 4, 4, 6]

Example 1: Squaring Number WITHOUT using List comprehensions

Suppose we want to create an output list which contains squares of all the numbers from 1 to 9. Let’s see how to do this using for loops and list comprehension.

Deciding When Not to Use a List Comprehension

List comprehensions are useful and can help you write elegant code that’s easy to read and debug, but they’re not the right choice for all circumstances. They might make your code run more slowly or use more memory. If your code is less performant or harder to understand, then it’s probably better to choose an alternative.

Watch Out for Nested Comprehensions

You can nest comprehensions to create combinations of lists, dictionaries, and sets within a collection. For example, say a climate laboratory is tracking the high temperature in five different cities for the first week of June. The perfect data structure for storing this data could be a Python list nested within a dictionary. You can create the data using nested comprehensions:


>>> cities = ["Austin", "Tacoma", "Topeka", "Sacramento", "Charlotte"] >>> {city: [0 for _ in range(7)] for city in cities} { 'Austin': [0, 0, 0, 0, 0, 0, 0], 'Tacoma': [0, 0, 0, 0, 0, 0, 0], 'Topeka': [0, 0, 0, 0, 0, 0, 0], 'Sacramento': [0, 0, 0, 0, 0, 0, 0], 'Charlotte': [0, 0, 0, 0, 0, 0, 0] }

You create the outer dictionary with a dictionary comprehension. The expression is a key-value pair that contains yet another comprehension. This code will quickly generate a list of data for each city in

cities

.

Nested lists are a common way to create matrices, which you’ll often use for mathematical purposes. Take a look at the code block below:


>>> [[number for number in range(5)] for _ in range(6)] [ [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4] ]

The outer list comprehension

[... for _ in range(6)]

creates six rows, while the inner list comprehension

[number for number in range(5)]

fills each of these rows with values.

So far, the purpose of each nested comprehension is pretty intuitive. However, there are other situations, such as flattening lists, where the logic arguably makes your code more confusing. Take this example, which uses a nested list comprehension to flatten a matrix:


matrix = [ ... [0, 0, 0], ... [1, 1, 1], ... [2, 2, 2], ... ] >>> [number for row in matrix for number in row] [0, 0, 0, 1, 1, 1, 2, 2, 2]

The code to flatten the matrix is concise, but it may not be so intuitive to understand how it works. On the other hand, if you used

for

loops to flatten the same matrix, then your code would be much more straightforward to understand:


>>> matrix = [ ... [0, 0, 0], ... [1, 1, 1], ... [2, 2, 2], ... ] >>> flat = [] >>> for row in matrix: ... for number in row: ... flat.append(number) ... >>> flat [0, 0, 0, 1, 1, 1, 2, 2, 2]

Now you can see that the code traverses one row of the matrix at a time, pulling out all the elements in that row before moving on to the next one.

Choose Generators for Large Datasets

A list comprehension in Python works by loading the entire output list into memory. For small or even medium-sized lists, this is generally fine. If you want to sum the squares of the first one-thousand integers, then a list comprehension will solve this problem admirably:


>>> sum([number * number for number in range(1000)]) 332833500

But what if you wanted to sum the squares of the first billion integers? If you tried that on your machine, then your computer might become unresponsive. That’s because Python is trying to create a list with one billion integers, which consumes more memory than your computer would like. If you tried to do it anyway, then your machine could slow down or even crash.

When the size of a list becomes problematic, it’s often helpful to use a generator instead of a list comprehension in Python. A generator doesn’t create a single, large data structure in memory, but instead returns an iterable. Your code can ask for the next value from the iterable as many times as necessary or until you’ve reached the end of your sequence, while only storing a single value at a time.

If you sum the first billion squares with a generator, then your program will likely run for a while, but it shouldn’t cause your computer to freeze. In the example below, you use a generator:


>>> sum(number * number for number in range(1_000_000_000)) 333333332833333333500000000

You can tell this is a generator because the expression isn’t inside brackets or curly braces. Optionally, generators can be inside parentheses.

The example above still requires a lot of work, but it performs the operations lazily. Because of lazy evaluation, your code only calculates values when they’re explicitly requested. After the generator yields a value, it can add that value to the running sum, then discard that value and generate the next value. When the

sum()

function requests the next value, the cycle starts over. This process keeps the memory footprint small.

The

map()

function also operates lazily, meaning memory won’t be an issue if you choose to use it in this case:


>>> sum(map(lambda number: number * number, range(1_000_000_000))) 333333332833333333500000000

It’s up to you whether you prefer the generator expression or

map()

.

Profile to Optimize Performance

So, which approach is faster? Should you use list comprehensions or one of their alternatives? Rather than adhere to a single rule that’s true in all cases, it’s more useful to ask yourself whether or not performance matters in your specific circumstance. If not, then it’s usually best to choose whatever approach leads to the cleanest code!

If you’re in a scenario where performance is important, then it’s typically best to profile different approaches and listen to the data. The

timeit

library is useful for timing how long it takes chunks of code to run. You can use

timeit

to compare the runtime of

map()

,

for

loops, and list comprehensions:


>>> import random >>> import timeit >>> TAX_RATE = .08 >>> PRICES = [random.randrange(100) for _ in range(100_000)] >>> def get_price(price): ... return price * (1 + TAX_RATE) ... >>> def get_prices_with_map(): ... return list(map(get_price, PRICES)) ... >>> def get_prices_with_comprehension(): ... return [get_price(price) for price in PRICES] ... >>> def get_prices_with_loop(): ... prices = [] ... for price in PRICES: ... prices.append(get_price(price)) ... return prices ... >>> timeit.timeit(get_prices_with_map, number=100) 2.0554370979998566 >>> timeit.timeit(get_prices_with_comprehension, number=100) 2.3982384680002724 >>> timeit.timeit(get_prices_with_loop, number=100) 3.0531821520007725

Here, you define three methods that each use a different approach for creating a list. Then, you tell

timeit

to run each of those functions 100 times each, and

timeit

returns the total time it took to run those 100 executions.

As your code demonstrates, the biggest difference is between the loop-based approach and

map()

, with the loop taking 50 percent longer to execute. Whether or not this matters depends on the needs of your application.

Fine-tuning vs RAG
Fine-tuning vs RAG

Python3


input_list


output_list


[]


for


var


in


input_list:


if


var


output_list.append(var)


print


"Output List using for loop:"


, output_list)

Output:

Output List using for loop: [2, 4, 4, 6]

Example 2: Generating Even list using List comprehensions

Here we use the list comprehensions in Python. It creates a new list named

list_using_comp

by iterating through each element

var

in the

input_list

. Elements are included in the new list only if they satisfy the condition, which checks if the element is even. As a result, the output list will contain all even numbers.

Syntax for set comprehension in Python

The syntax for set comprehension is as follows.

newSet= { expression for element in iterable }

Description of the syntax:

  • The iterable may be any iterable object or data structure in Python from which we have to use the elements to create the new set.
  • The element denotes the element from the iterable that has to be included in the set.
  • The expression can be any mathematical expression derived from the element.
  • newSet is the name of the new set which has to be created from the elements of the iterable.

Let us discuss this syntax using an example. In the following example, we are given a list of 10 integers. We have to create a set of the triples of these integers. This can be done using set comprehension as follows.


myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] newSet = {element*3 for element in myList} print("The existing list is:") print(myList) print("The Newly Created set is:") print(newSet)

Output:


The existing list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] The Newly Created set is: {3, 6, 9, 12, 15, 18, 21, 24, 27, 30}

In the above example, we are given a list of 10 integers and we have created a set of triples of the elements of the given list. In the statement “newSet = {element *3 for element in myList}”, Set comprehension is used to create the newSet which contains triples of the elements in myList.

If you will compare the code with the syntax for set comprehension, the following observation can be made.

  1. mySet is the set whose elements have been used to create a new set. Hence mySet has been used in place of the iterable.
  2. We have created a new set with triples of the elements of myList. Hence, element*3 has been used in place of expression.

We can also use conditional statements in a set comprehension. The syntax for using conditional statements in set comprehension is as follows.

newSet= { expression for element in iterable if condition }

Description of the syntax:

  • The iterable may be any iterable object or data structure in Python from which we have to use the elements to create the new set.
  • The condition is a conditional expression using
  • The element denotes the element from the iterable that has to be included in the set.
  • The expression can be any mathematical expression derived from the element.
  • newSet is the name of the new set which has to be created from the elements of the iterable.

Let us discuss this syntax using an example. In the following example, we are given a list of 10 integers. We have to create a set of triples of even integers. This can be done using set comprehension as follows.


myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] newSet = {element*3 for element in myList if element % 2 ==0} print("The existing list is:") print(myList) print("The Newly Created set is:") print(newSet)

Output:


The existing list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] The Newly Created set is: {6, 12, 18, 24, 30}

In the above example, we have a list of 10 integers and we have created a set of triples of those elements of the given list which are even numbers. In the statement “newSet = {element *3 for element in myList if element % 2 == 0}”, Set comprehension is used to create the newSet which contains squares of the even elements in myList.

If we compare the code with the syntax for set comprehension, the following observation can be made.

  1. myList is the list whose elements have been used to create a new set. Hence myList has been used in place of the iterable.
  2. We have to create a new list with triples of the even elements of myList. Hence, element*3 has been used in place of expression.
  3. To select only the even elements, we have used a conditional statement “element % 2 == 0” at the place of condition.
Python Full Course for free 🐍
Python Full Course for free 🐍

What is List Comprehension in Python?

To begin with, one should be familiar with the meaning of both the terms, list, and comprehension.

Lists, also called arrays, are data types in programming languages. The classification or arrangement of data into different categories based on their characteristics are called data types. The most common examples of data types in Python include integers, strings, characters, int, floats, and Boolean. Lists are built-in versatile data types in Python that store a specific data category.

They store multiple items in a single variable and follow an index from 0 to 1 to number all the items. The first item in a list is marked 0, the second is marked 1, and so on. Moreover, the items in a list are arranged in a particular order. It means you cannot add an item in between. The new items automatically go to the end of the list. You can create a new list using Python’s list() constructor.

However, when you want to create a new list based on an existing list, you need to use comprehension in Python. It helps generate a concise code by creating new sequences from the existing sequences. This is one of the biggest advantages of using Python. It allows you to write clear, easy-to-read code.

There are four types of comprehension in Python for different data types – list comprehension, dictionary comprehension, set comprehension, and generator comprehension.

Here, we’re talking about what is list comprehension in Python. Simply put, it is a function that allows you to create a new list from an existing list without writing elaborate code. You can use Python’s list comprehension to generate any existing list output. Let us look at an example.

ALSO READ: What is Python Coding? The Ultimate Guide

Consider a List of Even Numbers

L1 (2, 4, 6, 8, 10).

Now, if you want the square of all numbers present in list 1, you can use list comprehension.

Here is how you can do it.

square = [item**2 for items in L1]

print (square)

Output = [4, 16, 36, 64, 100]

Important Elements of List Comprehension

  • There is an input sequence or the existing list from which a new list is prepared.
  • A variable represents the items contained in an input sequence.
  • You can also add a condition to create a new list from the existing list by using a predicate function.
  • Output is generated from the input sequence by satisfying the predicate expression.

The syntax of list comprehension in Python consists of square brackets followed by a ‘for’ or ‘if’ clause called predicate expression. Here are some examples to help you better understand what is list comprehension in Python:

Example 1: Creating a new list using for

list1 = [8, 9, 10, 11]

new_cube_list = [item**3 for item in list 1]

print (new_cube_list)

Output = [512, 729, 1000, 1331]

Example 2: Creating a list of the first alphabet of every word in an existing list.

list1 = (‘red’, ‘green’, ‘blue’, ‘yellow’, ‘black’, ‘pink’)

new_word_list = [ word[0] for word in list1]

print (new_word_list)

Output = [‘r’, ‘g’, ‘b’, ‘y’, ‘b’, ‘p’]

ALSO READ: 5 Best Books on Python for Beginners and Experts in 2023

Create a Set from List using Comprehension

Here, I create a list with string values and use this with comprehension to create Python sets. The following example creates a set with all elements from the list.


# Consider 4 strings in a list list1 = ["wecome","to","sparkby","examples"] print("List : ",list1) # Create set from the list converted = {i for i in list1} print("Set: ",converted) # Output: # List : ['wecome', 'to', 'sparkby', 'examples'] # Set: {'wecome', 'examples', 'sparkby', 'to'}

List Comprehension in Python 🐍 with Execution | Best Python Tutorials for Beginners
List Comprehension in Python 🐍 with Execution | Best Python Tutorials for Beginners

Python3


list_using_comp


[var


for


var


in


range


10


)]


print


"Output List using list comprehension:"


list_using_comp)

Output:

Output List using list comprehension: [1, 4, 9, 16, 25, 36, 49, 64, 81]

When to Not Use List Comprehension

Even though list comprehension can make writing codes easier, you do not have to use it every time. You should not use list comprehension in the following circumstances.

Elaborate Code

When your code is too elaborate or complex, it is better to avoid list comprehension as it can be difficult to understand the code and hamper its performance. You can consider using a loop or other functions if the list comprehension expression is too lengthy.

No Use of Existing List

The whole purpose of using list comprehension in Python is to generate a new list that is related to or dependent on an existing list. However, if you don’t have to modify an existing list, you should not use list comprehension.

Writing Matrix

You should not use list comprehension when you are writing a matrix because it flattens the code and makes it difficult to understand.

The majority of programming languages have the same basic structure. If you want to be a programmer or build a career in the IT sector, it is essential to learn basic concepts like what is list comprehension in Python. It is one of the most popular questions in software developer interviews. Emeritus’ online courses on coding will help you learn the fundamentals of programming and offer practical training to boost your career in the IT sector.

By Sneha Chugh

Write to us at [email protected]

Lists are a helpful and frequently used feature in Python.

And list comprehension gives you a way to create lists while writing more elegant code that is easy to read.

In this beginner-friendly article, I’ll give an overview of how list comprehension works in Python. I’ll also show plenty of code examples along the way.

Let’s get started!

Python zip function 🤐
Python zip function 🤐

6.2 Examples of Filtering the Set using the Set Comprehension

Below I have converted several python set comprehension examples that filter the elements from the existing and create a new set.

Example 1

Here, We create a set with some integers and filter the elements that are greater than 25 using set comprehension by specifying the condition inside it.


# Consider the set with some integers myset = {12,34,56,3,45,67,89,1,6} print("Actual set:",myset) # Create set by filtering greater than 25 using set comprehension. set_comprehension = {i for i in myset if i > 25} print(set_comprehension) # Output: # Actual set: {1, 34, 3, 67, 6, 12, 45, 56, 89} # {34, 67, 45, 56, 89}

Example 2

We have a set with some integers, Now we created a set that hold elements that are less than 25 using set comprehension by specifying the condition inside it. Finally the filtered set hold only 4 elements.


# Consider the set with some integers myset = {12,34,56,3,45,67,89,1,6} print("Actual set:",myset) # Create set by filtering less than 25 using set comprehension. set_comprehension = {i for i in myset if i < 25} print(set_comprehension) # Output: # Actual set: {1, 34, 3, 67, 6, 12, 45, 56, 89} # {1, 3, 12, 6}

Example 3

Here, we used set comprehension to convert the data type of all elements present in the set to string. After we are displaying each element type.


# Consider the set with some integers myset = {12,34,56} print("Actual set:",myset) # Convert all the elements in the set to strings. set_comprehension = {str(i) for i in myset} for i in set_comprehension: print(type(i)) # Output: # Actual set: {56, 34, 12} # # #

Introduction to Python Set comprehension

Suppose that you have the following set that consists of three tags:


tags = {'Django', 'Pandas', 'Numpy'}

Code language: Python (python)

To convert the tags in the set to another set of tags in lowercase, you may use the following

for

loop:


tags = {'Django', 'Pandas', 'Numpy'} lowercase_tags = set() for tag in tags: lowercase_tags.add(tag.lower()) print(lowercase_tags)

Code language: Python (python)

Output:


{'django', 'numpy', 'pandas'}

Code language: Python (python)

How it works:

  • First, iterate over each element of the

    tags

    set.
  • Second, convert each tag to lowercase and add it the new set (

    lowercase_tags

    )

Or you can use the built-in

map()

function with a lambda expression:


tags = {'Django', 'Pandas', 'Numpy'} lowercase_tags = set(map(lambda tag: tag.lower(), tags)) print(lowercase_tags)

Code language: Python (python)

The

map()

function returns a map object so you need to use the

set()

function to convert it to a set.

To make the code more concise, Python provides you with the set comprehension syntax as follows:


{expression for element in set if condition}

Code language: Python (python)

The set comprehension allows you to create a new set based on an existing set.

A set comprehension carries the following steps:

  • First, iterate over the elements of a set.
  • Second, apply an

    expression

    to each element
  • Third, create a new set of elements resulting from the expression.

In addition, the set comprehension allows you to select which element to apply the expression via a

condition

in the

if

clause.

Note that the set comprehension returns a new set, it doesn’t modify the original set.

Back to the previous example, you can convert all the tags in the

tags

set by using the following set comprehension:


tags = {'Django', 'Pandas', 'Numpy'} lowercase_tags = {tag.lower() for tag in tags} print(lowercase_tags)

Code language: Python (python)

This syntax definitely looks more concise than a for loop and more elegant than the

map()

function.

Python Set comprehension with an if clause example

Suppose you want to convert all elements of the

tags

set to lowercase except for the

Numpy

.

To do it, you can add a condition to the set comprehension like this:


tags = {'Django', 'Pandas', 'Numpy'} new_tags = {tag.lower() for tag in tags if tag != 'Numpy'} print(new_tags)

Code language: Python (python)

Output:


{'django', 'pandas'}

Code language: Python (python)

Sets comprehension : Python tutorial 139
Sets comprehension : Python tutorial 139

Python3


input_list


set_using_comp


{var


for


var


in


input_list


if


var


print


"Output Set using set comprehensions:"


set_using_comp)

Output:

Output Set using set comprehensions: {2, 4, 6}

Python3


input_list


output_dict


{}


for


var


in


input_list:


if


var


output_dict[var]


var


print


"Output Dictionary using for loop:"


,output_dict )

Output:

Output Dictionary using for loop: {1: 1, 3: 27, 5: 125, 7: 343}

Example 2: Generating odd number with their cube values with using dictionary comprehension

We are using dictionary comprehension in Python. It initializes an

list

containing numbers from 1 to 7. It then constructs a new dictionary using dictionary comprehension. For each odd number

var

in the

list

, it calculates the cube of the number and assigns the result as the value to the key

var

in the dictionary.

Python Dictionary Comprehensions (+ Advanced Filtering and if/else Statements)
Python Dictionary Comprehensions (+ Advanced Filtering and if/else Statements)

Create Set from Existing Set using Set Comprehension

Here, first, we created a set that holds 9 integers, and we used it to create the new set from the existing set by subtracting 3 from each element in the list by using python set comprehension.


# Consider the set with some integers myset = {12,34,56,3,45,67,89,1,6} print("Actual set:",myset) # Create set by substracting set_comprehension = {i-3 for i in myset} print(set_comprehension) # Output: # Actual set: {1, 34, 3, 67, 6, 12, 45, 56, 89} # {0, 64, 3, 9, 42, 53, 86, -2, 31}

Keywords searched by users: set comprehension in python

Python Dictionary Comprehension
Python Dictionary Comprehension
Algorithms - Set Comprehension - Youtube
Algorithms – Set Comprehension – Youtube
2: Python List, Set & Dictionary Comprehension | Python Best Practices -  Youtube
2: Python List, Set & Dictionary Comprehension | Python Best Practices – Youtube
Algorithms - Set Comprehension - Youtube
Algorithms – Set Comprehension – Youtube
Set Comprehension In Python (Hindi) - Youtube
Set Comprehension In Python (Hindi) – Youtube
Python List Comprehension Tutorial | Datacamp
Python List Comprehension Tutorial | Datacamp
When To Use A List Comprehension In Python – Real Python
When To Use A List Comprehension In Python – Real Python
Python Dictionary Comprehension [7 Methods] - Python Guides
Python Dictionary Comprehension [7 Methods] – Python Guides

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *