简体   繁体   中英

python 3.7.1 cannot append inline after split

I am currently trying to participate in a few one-liner contests and I noticed some weird behaviour that make it hard.

this
"a,b,c".split(",").append("d")
returns None, while this:
l = "a,b,c".split(",")
l.append("d")

correctly returns ["a","b","c","d"]
Is it a known issue or is it normal behaviour? Documentation says that split returns a list of strings.
I am using python 3.7.1, version from October 22 in the Arch official repos.

l.append("d") returns None just like the other call. It mutates the list l which is called on though (which it also does in the other call, but there you have no reference to the list object):

>>> l = "a,b,c".split(",")
>>> l.append("d") is None  # the append call still returns None
True
>>> l  # it does, however, mutate the list
['a', 'b', 'c', 'd']

In order to get the same result in a single line, you can just use plain concatenation:

l = "a,b,c".split(",") + ["d"]

If (for some reason) you want to use list.append and get the resulting list in a one-liner, you would have to resort to some evil-doing like molesting a generator or comprehension for side effects (don't do that in serious code!):

l = next(x for x in ("a,b,c".split(","),) if not x.append("d"))

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