List comprehension is the use of some expression inside square braces []
to produce lists, it is a faster and more readable way for creating lists.
list = [expression for item in list] **Examples:**
Creating list with range
:
digits = [x for x in range(10)]
print(digits)
Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Multiplying Parts of a List:
multiples_of_three = [ x*3 for x in range(10) ]
print(multiples_of_three)
Output = [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
Show the first letter of each word using Python:
authors = [“Ernest Hemingway”,”Langston Hughes”,”Frank Herbert”,”Toni Morrison”, “Emily Dickson”,”Stephen King”]
letters = [ name[0] for name in authors ]
print(letters)
Output = [‘E’, ‘L’, ‘F’, ‘T’, ‘E’, ‘S’]
Adding condition to pick from lists:
user_data = “Elvis Presley 987-654-3210”
phone_number = [ x for x in user_data if x.isdigit()]
print(phone_number)
Output: [‘9’, ‘8’, ‘7’, ‘6’, ‘5’, ‘4’, ‘3’, ‘2’, ‘1’, ‘0’]
Different types of functions and conditions can be applied to the item and after list.