Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to spread a python array [duplicate]

Tags:

python

In JS I can do this

const a = [1,2,3,4] const b = [10, ...a] console.log(b) // [10,1,2,3,4] 

Is there a similar way in python?

like image 890
Alex Cory Avatar asked Jan 25 '18 20:01

Alex Cory


People also ask

How do you repeat an array in Python?

In Python, if you want to repeat the elements multiple times in the NumPy array then you can use the numpy. repeat() function. In Python, this method is available in the NumPy module and this function is used to return the numpy array of the repeated items along with axis such as 0 and 1.

How do you repeat an element in an array?

The repeat() function is used to repeat elements of an array. Input array. The number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis.

How do you spread an object in Python?

The JavaScript spread operator (...) is a useful and convenient syntax for expanding iterable objects into function arguments, array literals, or other object literals. Python contains a similar “spread” operator that allows for iterable unpacking.


2 Answers

As Alexander points out in the comments, list addition is concatenation.

a = [1,2,3,4] b = [10] + a  # N.B. that this is NOT `10 + a` # [10, 1, 2, 3, 4] 

You can also use list.extend

a = [1,2,3,4] b = [10] b.extend(a) # b is [10, 1, 2, 3, 4] 

and newer versions of Python allow you to (ab)use the splat (*) operator.

b = [10, *a] # [10, 1, 2, 3, 4] 

Your choice may reflect a need to mutate (or not mutate) an existing list, though.

a = [1,2,3,4] b = [10] DONTCHANGE = b  b = b + a  # (or b += a) # DONTCHANGE stays [10] # b is assigned to the new list [10, 1, 2, 3, 4]  b = [*b, *a] # same as above  b.extend(a) # DONTCHANGE is now [10, 1, 2, 3, 4]! Uh oh! # b is too, of course... 
like image 52
Adam Smith Avatar answered Sep 21 '22 17:09

Adam Smith


The question does not make clear what exactly you want to achieve.

To replicate that operation you can use the Python list extend method, which appends items from the list you pass as an argument:

>>> list_one = [1,2,3] >>> list_two = [4,5,6] >>> list_one.extend(list_two) >>> list_one [1, 2, 3, 4, 5, 6] 

If what you need is to extend a list at a specific insertion point you can use list slicing:

>>> l = [1, 2, 3, 4, 5] >>> l[2:2] = ['a', 'b', 'c'] >>> l [1, 2, 'a', 'b', 'c', 3, 4, 5] 
like image 21
Francisco Jiménez Cabrera Avatar answered Sep 22 '22 17:09

Francisco Jiménez Cabrera