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.

4
  • 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. Commented Aug 25, 2021 at 16:21
  • 2
    Does this answer your question? How to spread a python array, or How do I concatenate two lists in Python? Commented Aug 25, 2021 at 16:21
  • You can use *. So, [1, 2, *bar, 5, 6] or for your example, [*foo, *bar] Commented Aug 25, 2021 at 16:24
  • What about the rest syntax? As shown in the second example. Commented Aug 25, 2021 at 16:40

1 Answer 1

2

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] 
Sign up to request clarification or add additional context in comments.

4 Comments

This is a clear duplicate with similar but more complete answers
Apologies, I didnt search I just answered, my bad.
The direct equivalent in Python would be *, so [*listOne, *listTwo]
Very good point, edited to reflect

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.