Optimise your code with list comprehension in python

Published: 26 November 2023
on channel: INFY TECH
86
6

List comprehensions are a powerful tool that can be used to write concise and efficient code. They are a great way to work with lists and can be used to perform many different operations on them.

List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.

Example:

Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name.

Without list comprehension, you will have to write a for statement with a conditional test inside:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []

for x in fruits:
if "a" in x:
newlist.append(x)

print(newlist)

With list comprehension, you can do all that with only one line of code:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)


Watch video Optimise your code with list comprehension in python online without registration, duration hours minute second in high quality. This video was added by user INFY TECH 26 November 2023, don't forget to share it with your friends and acquaintances, it has been viewed on our site 86 once and liked it 6 people.