close

How to spread a python array

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to spread a python array in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to spread a python array?

  1. How to spread a python array?

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

  2. spread a python array

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

Method 1

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...

Method 2

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]

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read