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.
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!
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.
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.
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.
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With