Home » Python

List Comprehension in Python

Python | List Comprehension: In this tutorial, we are going to learn about the List Comprehension with examples in Python.
Submitted by Sapna Deraje Radhakrishna, on November 19, 2019

In order to create a list, a most obvious and remembered solution is to use a for-loop.

Example:

Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> flights = {'09:35':'Long Beach', '10:00':'los-angeles', '11:00':'san jose'}
>>> flight_time_list = []
>>> for key in flights.keys():
...     flight_time_list.append(key)
...
>>> print(flight_time_list)
['09:35', '10:00', '11:00']
>>>

Python's built-in comprehension feature that lets us reduce the number of lines in list creation to a single line.

Example:

-bash-4.2$ python3
Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> flights = {'09:35':'Long Beach', '10:00':'los-angeles', '11:00':'san jose'}
>>> flight_time_list = [ key for key in flights.keys()]
>>> print(flight_time_list)
['09:35', '10:00', '11:00']
>>>

Syntax for list comprehension

The list comprehension starts with a [ and ], to ensure that the result is a list.

    [expression for item in list]

The comprehension can also utilize the if condition.

Example: Grouping the common items to a list

Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> grade_k = ['maddy', 'sriansh', 'owen', 'molly']
>>> grade_first = ['molly', 'owen', 'ricky', 'sid']
>>> common_names = [a for a in grade_k for b in grade_first if a==b]
>>> print(common_names)
['owen', 'molly']
>>>

Advantages of using Comprehension

  1. Comprehensions requires less code. Python interpreter is optimized to run comprehensions as quickly as possible.
  2. Comprehensions execute faster than for loop.
  3. Comprehensions can be used in places where for loop cannot be used. All the comprehensions appear to the right of the assignment operator, which is something for loop cannot do.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.