List Comprehensions in Python || Lesson 22.1 || Python || Learning Monkey ||
#pytho #learningmonke #pythoncodin #placement #pythontutorial #pythoncours #pythonforbeginner #pythonfordatascienc #pythonfullcours #pythonprogrammin #pythonfreecourse
List Comprehensions in Python
In this class, we discuss list comprehensions in Python.
List Comprehensions
The reader should have some prior knowledge of the list data type. Click here.
List comprehensions are one of the ways to create a list.
List comprehensions help in writing elegant and user-friendly code.
The list comprehensions consist of expressions and context.
Take example and understand expression and context in a list comprehension.
Example: [x**2 for x in range(1,7)]
From the above example, x**2, we call expression.
The remaining part for x in range(1,7) we call context.
Both expression and context are placed in a list.
The above example context is generating numbers from 1,2,3,4,5,6.
The numbers generated by the context expression are evaluated. And the result is placed in the list.
Output: [1,4,9,16,25,36]
The same output can be created using the traditional way by writing a loop and appending the value to the list.
List comprehension is easy and elegant to write the code.
Context
The context part in list comprehension consists of the arbitrary number of for and if statements.
Example: [x**2 for x in range(1,7)if x%2==0]
The comprehension mentioned above display a list [4,16,36]
For statement generate the numbers. On the generated numbers, if the condition is applied.
If the condition is true, evaluate the expression.
The list comprehension evaluates in the way mentioned above.
Example:
employees=[[“rajesh”,2000],[“suresh”,5000],[“mahesh”,7000],[“suraj”,9000]]
z=[x for x,y in employees if y 5000]
print(z)
Output: [“Mahesh”,”suraj”]
Example with two if conditions
employees=[[“rajesh”,2000],[“suresh”,5000],[“mahesh”,7000],[“suraj”,9000]]
z=[x for x,y in employees if y 5000 if x==’mahesh’]
print(z)
The above example will display. [“mahesh”]
If both the if conditions are true. Then the expression is evaluated.
List comprehension containing two for loops.
How will it get executed?
Example:
z=[(x,y)for x in range(3) for y in range(3) if x!=y]
print(z)
Output: [(0,1),(0,2),(1,0),(1,2),(2,0)(2,1)]
If else statement in comprehension example
z=[(x if x%2==1 else x-1) for x in range(10)]
print(z)
If condition satisfies expression evaluates. Otherwise, else will execute.
Output: [-1,1,1,3,3,5,5,7,7,9]
Link for playlists:
https://www.youtube.com/channel/UCl8x4Pn9Mnh_C1fue-Yndig/playlists
Link for our website: https://learningmonkey.in
Follow us on Facebook @ https://www.facebook.com/learningmonkey
Follow us on Instagram @ https://www.instagram.com/learningmonkey1/
Follow us on Twitter @ https://twitter.com/_learningmonkey
Mail us @ [email protected]
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «List Comprehensions in Python || Lesson 22.1 || Python || Learning Monkey ||», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.