简体   繁体   中英

How to assign a value to variable while extending a list?

it is possible to assign a value to a variable, in the command "extend"?

for example:

ele1=[]
ele2=[]
list=[ele1,ele2]
list[0].extend([a=1,b="bla"])

instead of:

ele1=[]
ele2=[]
list=[ele1,ele2]
a=1
b="bla"
list[0].extend([a,b])

Python distinguishes between "expressions", which have a value and can be generally used wherever a value is needed, and "statements", which perform some action, do not have a value, and cannot be placed in a spot where a value is needed.

Assignment is a statement, and cannot be embedded as a value anywhere, including in a list literal.

(This often comes as surprise to people coming from C-like languages, which do make assignment an expression, but which can often lead to hard-to-find bugs when people, eg, confuse = and == in conditionals.)

No, Python doesn't allow assignment inside expressions (because it's a great source of bugs) but there are other ways to write your example without the repetition. eg.

a, b = ele1 = [1, "bla"]
ele2 = []
lst = [ele1, ele2]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM