Tuesday, November 12, 2019

List Comprehension in Python With Examples

List comprehension in Python is a simple way to create a List from an iterable, it consists of an expression, a loop, an iterable that is iterated using the loop and an optional condition enclosed in a bracket.

Syntax of list comprehension in Python is as given below-

other_list = [expression for iterable_items if condition]

Here for loop is used to generate items for the list by iterating the items of the given iterable. Optional condition is used to filter items if required.

The syntax of list comprehension is equivalent to the following traditional way of list creation-

other_list = []
for item in iterable:
 if condition:
  other_list.append(expression_using_item)

List comprehension Python examples

1. A simple example using the for loop with a range function to create a list of numbers with in a given range.

num_list = [num for num in range(1, 5)]
print(num_list) # [1, 2, 3, 4]

2. Creating a list by iterating alphabets of a word in a String.

name = 'Michael'
alphabet_list = [a for a in name]
print(alphabet_list) #['M', 'i', 'c', 'h', 'a', 'e', 'l']

3. Creating list from another list where each element of the list is multiplied by 2.

num_list = [2, 4, 6, 8]

another_list = [num * 2 for num in num_list]
print(another_list) # [4, 8, 12, 16]

4. List comprehension example of list creation using another list where if condition is also used to filter out items.

name_list = ['Michael', 'Jay', 'Jason', 'Ryan']
another_list = [a for a in name_list if len(a) >= 5]
print(another_list) #['Michael', 'Jason']

5. Sum of the items of two lists to create a new list using list comprehension.

num_list1 = [1, 2, 3, 4]
num_list2 = [5, 6, 7, 8]

another_list = [num_list1[i]+num_list2[i] for i in range(len(num_list1))]
print(another_list) #[6, 8, 10, 12]

6. Find common elements between two lists using list comprehension.

num_list1 = [1, 2, 3, 4]
num_list2 = [4, 8, 2, 5]

common_list = [a for a in num_list1 for b in num_list2 if a == b]
print(common_list) # [2, 4]

That's all for this topic List Comprehension in Python With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. List in Python With Examples
  2. Tuple in Python With Examples
  3. Python Conditional Statement - if, elif, else Statements
  4. Python Generator, Generator Expression, Yield Statement
  5. Magic Methods in Python With Examples

You may also like-

  1. Variable Length Arguments (*args), Keyword Varargs (**kwargs) in Python
  2. Python Program to Check Armstrong Number
  3. Interface in Python
  4. Accessing Characters in Python String
  5. How LinkedList Class Works Internally in Java
  6. StampedLock in Java
  7. Constructor Chaining in Java
  8. How to Create PDF From XML Using Apache FOP