List Comprehension

List Comprehension is defined as an elegant way to define, create a list in Python and consists of brackets that contains an expression followed by for clause. It is efficient in both computationally and in terms of coding space and time.

Signature

The list comprehension starts with '[' and ']'.

[ expression for item in list if conditional ]

Example

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

Output:

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

Example

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

Output:

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

Example

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

Output:

Output
OS
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents