Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

proper use of list comprehensions - python

Tags:

People also ask

What are list comprehensions used for?

List comprehension is an elegant way to define and create lists based on existing lists. List comprehension is generally more compact and faster than normal functions and loops for creating list. However, we should avoid writing very long list comprehensions in one line to ensure that code is user-friendly.

How do list comprehensions work in Python?

List comprehensions provide us with a simple way to create a list based on some sequence or another list that we can loop over. In python terminology, anything that we can loop over is called iterable. At its most basic level, list comprehension is a syntactic construct for creating lists from existing lists.

What are some of the advantages of using list comprehensions?

Some of the benefits are as follows: List Comprehensions are easy to understand and make code elegant. We can write the program with simple expressions. List comprehensions are way faster than for loop and other methods like a map.

Are list comprehensions better than for loops?

Because of differences in how Python implements for loops and list comprehension, list comprehensions are almost always faster than for loops when performing operations.


Normally, list comprehensions are used to derive a new list from an existing list. Eg:

>>> a = [1, 2, 3, 4, 5]
>>> [i for i in a if i > 2]
[3, 4, 5]

Should we use them to perform other procedures? Eg:

>>> a = [1, 2, 3, 4, 5]
>>> b = []
>>> [b.append(i) for i in a]
[None, None, None, None, None]
>>> print b
[1, 2, 3, 4, 5]

or should I avoid the above and use the following instead?:

for i in a:
    b.append(i)