Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: List comprehension to assign different values

I'm making a 2D list and I would like to initialize it with a list comprehension. I would like it to do something like this:

[[x for i in range(3) if j <= 1: x=1 else x=2] for j in range(3)]

so it should return something like:

[[1,1,1],
 [1,1,1],
 [2,2,2]]

How might I go about doing this?

Thanks for your help.

like image 218
Nope Avatar asked Oct 05 '09 23:10

Nope


People also ask

Can you assign variables in list comprehension Python?

Now, on a practical note: you build up a list with two square brackets; Inside these brackets, you'll use commas to separate your values. You can then assign your list to a variable. The values that you put in a Python list can be of any data type, even lists!

Can you assign in list comprehension?

As mentioned in the above answers there is no direct assignment possible in the list comprehension feature, but there is a hackable way to do it using the exec method to achieve the assignment. Not just assignments we can pas any python expression in exec method to evaluate it. Save this answer.

How do you assign a value from one list to another in Python?

List copy using =(assignment operator) This is the simplest method of cloning a list by using = operators. This operator assigns the old list to the new list using Python = operators. Here we will create a list and then we will copy the old list into the new list using assignment operators.

How do you use assignment operator in list comprehension Python?

In the if-statement of the list comprehension we call function f and assign the value to y if the result of f(x) makes the condition become True . If we want to add the result of f(x) to the list we'd have to call f(x) again without the Walrus Operator or write a for-loop where we can use a temporary variable.


1 Answers

It appears as though you're looking for something like this:

[[1 if j <= 1 else 2 for i in range(3)] for j in range(3)]

The Python conditional expression is a bit different from what you might be used to if you're coming from something like C or Java:

The expression x if C else y first evaluates C (not x); if C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.

A slightly shorter way to do the same thing is:

[[1 if j <= 1 else 2]*3 for j in range(3)]
like image 149
Greg Hewgill Avatar answered Sep 22 '22 15:09

Greg Hewgill