is there a function in python (or some library) that allows me to add items to a list that returns a list?
preferably a new list.
so an imperative style would be
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
I'd like to go
thislist = ["apple", "banana", "cherry"]
newlist = thislist.cons("orange")
print(newlist)
I can obviously write such a thing, but this would seem to be (for someone from a functional background) a pretty basic tool in the toolkit
CodePudding user response:
There is
. Put orange in a new list, then add them together:
thislist = ["apple", "banana", "cherry"]
newlist = thislist ["orange"]
print(newlist)
CodePudding user response:
I would generally recommend @Soren's answer because it is more readable and "pythonic", but worth mentioning that there is another option that can occasionally be useful:
thislist = ["apple", "banana", "cherry"]
newlist = [*thislist, "orange"]
print(newlist)