'Combine a simple value with a list
[What's the idiomatic syntax for prepending to a short python list? is about modifying an existing list, and doesn't contain a suitable answer to this question. While a solution can be found in one its answers, it's not the best one.]
Is there a simple way to combine simple values and/or the elements of a list into a flat list?
For example, given
lst = [ 5, 6, 7 ]
x = 4
Is there a simple way to produce
result = [ 4, 5, 6, 7 ]
The following is satisfactory, but I'm sure there's a cleaner way to do this:
result = [ x ]
result.extend(lst)
Perl:
my @array = ( 5, 6, 7 );
my $x = 4;
my @result = ( $x, @array );
JavaScript (ES6):
let array = [ 5, 6, 7 ];
let x = 4;
let result = [ x, ...list ];
Solution 1:[1]
You can concatenate two lists (or two tuples).
result = [x] + lst
You could use the iterable unpacking operator on arbitrary iterables.
result = [x, *lst]
If you have a iterable you only want to make look flat rather than actually flattened, you can use itertools.chain
to create an iterable generator.
import itertools
result = itertools.chain([x], lst)
If you're ok with prepending to the existing list instead of creating a new one, solution can be found here.
Solution 2:[2]
There is indeed, you have the +
operator to concatenate lists
[x] + [ 5, 6, 7 ]
# [4, 5, 6, 7]
You could also use the iterable unpacking operator:
l = [ 5, 6, 7 ]
[x, *l]
[4, 5, 6, 7]
Or you can also use list.insert
:
l.insert(0, x)
print(l)
[4, 5, 6, 7]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Martijn Pieters |