Learn Python – Python List Comprehension- Basic and advance

List Comprehension is defined as an based way to define, create a list in Python and consists of brackets that incorporates an expression followed by using for clause. It is environment friendly in each computationally and in phrases of coding space and time.

Signature

The list comprehension starts with ‘[‘ and ‘]’.

[ expression for item in list if conditional ]

Example

letters = []  
for letter in 'Python':  
    letters.append(letter)  
print(letters)  

Output:

['P', 'y', 't', 'h', 'o', 'n']

Example

letters = [ letter for letter in 'Python' ]  
print( letters)  

Output:

['P', 'y', 't', 'h', 'o', 'n']

Example

x = {'chrome': 'browser', 'Windows': 'OS', 'C': 'language'}  
x['mouse'] = 'hardware'  
print(x['Windows'])  

Output:

OS