-4

[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 ];
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • 1
    `y = [x] + list` – Tom Dalton Jan 20 '20 at 17:25
  • 2
    The closest analogue to the Perl and Javascript syntax in Python is `result = [x, *lst]` where `lst` is the other list. – kaya3 Jan 20 '20 at 17:36
  • Comments are not for extended discussion; a meta-conversation about whether or not this question is a duplicate has been [archived in chat](https://chat.stackoverflow.com/rooms/206935/discussion-on-question-by-ikegami-combine-a-simple-value-with-a-list). – Cody Gray - on strike Jan 30 '20 at 18:44

2 Answers2

4

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]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
yatu
  • 86,083
  • 12
  • 84
  • 139
-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.

ikegami
  • 367,544
  • 15
  • 269
  • 518