Optimise your code with list comprehension in python

Опубликовано: 26 Ноябрь 2023
на канале: 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)


Смотрите видео Optimise your code with list comprehension in python онлайн без регистрации, длительностью часов минут секунд в хорошем качестве. Это видео добавил пользователь INFY TECH 26 Ноябрь 2023, не забудьте поделиться им ссылкой с друзьями и знакомыми, на нашем сайте его посмотрели 86 раз и оно понравилось 6 людям.