Can't you shorten this Python code to one line?

Asked 2 years ago, Updated 2 years ago, 18 views

listx = 100
for i in list1:
    listx -= i

If you look at the Python for example, there are some of these features in one line, most of them

[i*2 for i in list1]

It's an example of appending a list like this.

But can't we set the value of a instead of appending to the list and make it a line to subtract the sequence made of the list?

python

2022-09-21 10:55

1 Answers

The expression Walrus operator has been added since 3.8.

If used well, you can create concise code.

In [1]: listx = 100                                                                                                                                                                                             

In [2]: [listx := listx - i for i in range(1, 10)]                                                                                                                                                              
Out[2]: [99, 97, 94, 90, 85, 79, 72, 64, 55]


2022-09-21 10:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.