List Comprehension | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 1

List Comprehension

I just wanted to ask if someone could give an easy explanation of "list comprehension" in python language.

18th Jun 2024, 5:02 PM
Chris
Chris - avatar
5 Réponses
+ 6
Chris , i think it is helpful to take a simple task and build a code that demonstrates how a for loop works, and how we can use a list comprehension instead. the task is to separate all even numbers in a new list. see the sample: https://sololearn.com/compiler-playground/cWdOIzooputr/?ref=app
18th Jun 2024, 6:12 PM
Lothar
Lothar - avatar
+ 3
It is an explanation of Lothar's code: # using a list comprehension nums = [99, 8, 13, 55, 12, 4, 0, 77, 99, 22, 2, 44, 76] even_nums = [num for num in nums if num % 2 == 0] The code extracts all even number from the given list "nums", and put them into a list. [num for num in nums if num % 2 == 0] Let's modify the above code into a stand for loop with a print function. for num in nums: if num % 2 == 0: print(num) As you guessed, it prints all the even numbers in the list. While the syntax is invalid, if you move the print(num) to the start of the statement: [print(num) for num in nums if num % 2 == 0] It will be something like [8, 12, 14, 0, 22, 2, 44, 76]. Finally, the "even number list" is assigned to variable even_nums, thus even_nums = [8, 12, 14, 0, 22, 2, 44, 76] and it finish the list comprehension.
19th Jun 2024, 1:29 AM
Wong Hei Ming
Wong Hei Ming - avatar
+ 2
It means you generate a list in one line instead of multiple ones. Like this. chad_names = [user.name for user in users if user.is_chad] It can be way faster, since the list is being created from a generator, instead of having to create an empty list and then add a new entry to it over and over.
18th Jun 2024, 5:23 PM
Wilbur Jaywright
Wilbur Jaywright - avatar
+ 1
Basically it's a short hand for mapping a list
18th Jun 2024, 7:03 PM
Jackson Scott
Jackson Scott - avatar