Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, working with list comprehensions

I have such code:

a = [[1, 1], [2, 1], [3, 0]]

I want to get two lists, the first contains elements of 'a', where a[][1] = 1, and the second - elements where a[][1] = 0. So

first_list = [[1, 1], [2, 1]] 

second_list = [[3, 0]]. 

I can do such thing with two list comprehension:

first_list = [i for i in a if i[1] == 1]

second_list = [i for i in a if i[1] == 0]

But maybe exists other (more pythonic, or shorter) way to do this? Thanks for your answers.

like image 1000
alexvassel Avatar asked May 27 '11 07:05

alexvassel


People also ask

Are list comprehensions good practice?

List comprehensions are great because they require less lines of code, are easier to comprehend, and are generally faster than a for loop.

Are Python list comprehensions fast?

List comprehensions are faster than for loops to create lists. But, this is because we are creating a list by appending new elements to it at each iteration. This is slow. Side note: It would even be worse if it was a Numpy Array and not a list.

Are list comprehensions generators?

List comprehensions and generators are not different at all; they are just different ways of writing the same thing. A list comprehension produces a list as output, a generator produces a generator object.

Can you do list comprehension with a set Python?

What is set comprehension in Python? Set comprehension is a method for creating sets in python using the elements from other iterables like lists, sets, or tuples. Just like we use list comprehension to create lists, we can use set comprehension instead of for loop to create a new set and add elements to it.


1 Answers

List comprehension are very pythonic and the recommended way of doing this. Your code is fine.

like image 52
Björn Pollex Avatar answered Oct 05 '22 22:10

Björn Pollex