chevron_left
933 points
8 4 2

Problem:

Hello guys,
I am new to python language and just complete the list concept in python and wanted to learn list comprehension and have learned about it but when I tried to implement one of the programs of, I am not able to implement it. below is the code so this is getting me mad because I come from a c language background so need help from someone.

Solution:

I have got your issue you are facing with it you want to implement the list comprehension in the python language so basically it is the single line implementation of the list with the if-else as you can say about it.
It basically provides a short and concise way to create the list because we enclosed it in the list as its syntax is defined with it. It is an elegant way to create a new list in just a single list with some condition, below is the example that will help you with it.
Syntax:

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

Example:

# Constructing output list WITHOUT 
# Using List comprehensions 
input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7] 

output_list = [] 

# Using loop for constructing output list 
for var in input_list: 
	if var % 2 == 0: 
		output_list.append(var) 

print("Output List using for loop:", output_list) 

I hope this is going to help you. Happy coding!!

More Posts

If else in one line python Naymul01 - Oct 20
If else in one line python sam_dev - Sep 21
Fix the error in the if-else statement. Naymul01 - 1 day
In an if construct, what statements are optional? Hafsa_Rao - Aug 7
What does null pointer exception mean in processing? Huzaifa-Glitch - May 23
Check if list is subset of another list python Naymul01 - Oct 19
Python check if string contains substring from list Naymul01 - Oct 5
Python check if string exists in list amna - Jul 5
How to check if a list is empty python Adnan Ajouri - Oct 21, 2020
PHP if...else...elseif Statements Tomas Herman - Jul 30