Simply concatenate lists using +
:
>>> d = [i for i in range(6)] + [50]
>>> d
[0, 1, 2, 3, 4, 5, 50]
Frage
I am basically looking for a one-liner to create a list using the python list comprehension feature, but also to add some extra value/values that do not fit the pattern. So for example I would like to get a list with the following values [1, 2, 3, 4, 5, 50]. I have tried the following:
a = [i for i in range(6), 50] # [[0, 1, 2, 3, 4, 5], 50]
b = [i for i in range(6)].append(50) # None
c = [i for i in range(6)].extend([50]) # None
Besides the actual answer, explanations about why none of my lists return the desired output are highly appreciated.
Lösung
Simply concatenate lists using +
:
>>> d = [i for i in range(6)] + [50]
>>> d
[0, 1, 2, 3, 4, 5, 50]
Andere Tipps
Just wanted to point out, that is not the only place you can do that addition, and in other places it makes more sense:
In [1]: d = [i for i in range(6)] + [50]
In [2]: print d
[0, 1, 2, 3, 4, 5, 50]
In [3]: d = [i for i in range(6) + [50]]
In [4]: print d
[0, 1, 2, 3, 4, 5, 50]
In [5]: d = [i*2 for i in range(6) + [50]]
In [6]: print d
[0, 2, 4, 6, 8, 10, 100]
In that case, it's a lot more useful to have a one-liner.
That won't work in python 3+ though, because xrange is not a list; it's a generator. The more general form uses itertools.chain
:
In [7]: d = [i*2 for i in xrange(6) + [50]]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-7-7c5dfed6c9b9> in <module>()
----> 1 d = [i*2 for i in xrange(6) + [50]]
TypeError: unsupported operand type(s) for +: 'xrange' and 'list'
In [8]: from itertools import chain
In [9]: d = [i*2 for i in chain(xrange(6),[50])]
In [10]: print d
[0, 2, 4, 6, 8, 10, 100]
The append()
and extend()
functions return None
since they modify the list in place, so that should explain that. If you wanted that to work you would need to do:
b = [i for i in range(6)]
b.append(50)
I don't know of any "pythonic" way to do it in one line aside from a
. Or as pointed out in the comments:
d = [i for i in range(6)] + AnotherListWithExtraCharacters
You can use add operator:
print [i for i in range(6)] + [50]
>>> [0, 1, 2, 3, 4, 5, 50]