Myfiles 123
Myfiles 123
List Comprehensions
------------------------------------------------
It is very compact way of creating list objects
l=[]
for i in range(1,11):
l.append(i)
print(l)
--------------------------
by using list comprehension
syntax:
[expression for each element in sequence]
===================================================
list comprehension with condition:
syntax:
[expression for each element in sequence if condition]
**********************************************
list comprehension application
l1=[10,20,30,40]
l2=[30,40,50,60]
*************************************************
l=['ravi','nilesh','rani','venki']
#create a new list only first letter from every word
------------------------------------------------
-----------------------------------------------
word_list=s.split()
print(word_list)
l=[[word.upper(),len(word)] for word in word_list]
print(l)
************************************************
interview Question
1.what is list comprehension explain with example
=============================================================================
#generate a new list from given sequence that satisfies two different condition
#e.g: calculating cubes of odd number and squares of even numbers
Syntax:[expression1 if condition else expression for eachelement in sequence]
-----------------------------------------------------------------------------------
---------------
===================================================================================
================
set comprehension possible in python
l=[10,20,55,66]
j={x:x*2 for x in l}
print(j)
=============================================================================
Tuple Comprehension:
------------------------------------
tuple comprehension not possible in python
t=(x*x for x in range(1,6))
print(t)
<generator object <genexpr> at 0x0000012DC7563030>