Issue
[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
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.
Answered By - ikegami
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.