Python List Comprehension with Examples | Live Practice

Spread the love

In this tutorial, you will learn about python List Comprehension with Examples, You can use this List Comprehension for Data Science and machine learning developments.

Def : It’s a process of creating new lists by using old lists with condition statements

Syntax : [ expression for loop if conditionals]

List Comprehension Advantages :

  • Less Code – single line statement.
  • Fast code execution when compare to function and map functions
  • Special uses cases in machine learning and data science projects

#python example programs on list comprehension

#Print odd and even numbers using list comprehensive method list = [1,2,3,4,5,6,7,8,9,10] even_numbers = [i for i in range(10) if(i%2==0) ] print(even_numbers) odd_numbers = [i for i in range(10) if(i%2!=0) ] print(odd_numbers)

Output:

[0, 2, 4, 6, 8]
[1, 3, 5, 7, 9]



#multiplication using list comprehension

multiplication = [5*i for i in list ] print(multiplication)

Output:

[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]

#functions in list comprehension

list = ["Hello Python", '3','Hi','5'] is_digit = [i for i in list if i.isdigit() ] print(is_digit)

Output:

['3', '5']
list = ["Hello Python"] lower = [i.lower() for i in list] print(lower)

Output:

['hello python']

To Uppercase :

list = ["Hello Python"] upper = [i.upper() for i in list] print(upper)

Output:

['HELLO PYTHON']

 

admin

admin

Leave a Reply

Your email address will not be published. Required fields are marked *