In python add a variable to a list in an if statement. I want to do something like this:
var = 1
vars = []
if var >= 1:
# add it to "vars"
pass
you need the append
method
var = 1
vars = []
if var >= 1:
vars.append(var)
var = 1
vars = []
if var >= 1:
vars.append(var)
If you are just adding a single element:
var = 1
vars = [var] if var >= 1 else []
It seems more logical that you would have many vars in some container so a list comp would be better:
vars = [1,2,1,2,4]
new_vars = [var for var in vars if var >= 2 ]
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.