-1

I am familiar with the spread/rest syntax in JavaScript:

// spread syntax
const foo = [1, 2];
const bar = [3, 4];

console.log([...foo, ...bar]); // [1, 2, 3, 4]

// rest syntax
function baz(...nums) {
  console.log(nums);
}

baz(1, 2, 3); // [1, 2 ,3]

I know how to concatenate arrays.

foo = [1, 2, 3]
bar = [*foo, 4, 5]
print(bar) # [1, 2, 3, 4, 5]

Is there a way to use the Rest Syntax in python?

PS: Look at the second JS example.

  • 1
    In JavaScript, `...` is not an "operator"; it's a syntax construct but it's not part of the expression grammar. In Python, you can use the `+` operator to do concatenation things on arrays. – Pointy Aug 25 '21 at 16:21
  • 2
    Does this answer your question? [How to spread a python array](https://stackoverflow.com/questions/48451228/how-to-spread-a-python-array), or [How do I concatenate two lists in Python?](https://stackoverflow.com/questions/1720421/how-do-i-concatenate-two-lists-in-python) – pilchard Aug 25 '21 at 16:21
  • You can use `*`. So, `[1, 2, *bar, 5, 6]` or for your example, `[*foo, *bar]` – juanpa.arrivillaga Aug 25 '21 at 16:24
  • What about the rest syntax? As shown in the second example. – Vikram Negi Aug 25 '21 at 16:40

1 Answers1

0

You can simply combine them, this has the same effect as the JS spread operator.

listOne = [1, 2, 3]
listTwo = [9, 10, 11]

joinedList = listOne + listTwo
// [1, 2, 3, 9, 10, 11]

As pointed out in the comments, the direct equivalent would be to use the * operator.

joinedList = [*listOne, *listTwo]
omeanwell
  • 1,847
  • 1
  • 10
  • 16