Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

how to spread an array in python

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

python array spread

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

PREVIOUS NEXT
Code Example
Python :: how to use underscore in python 
Python :: time series python 
Python :: install multiple versions of python 
Python :: python bigquery example 
Python :: python how to get rid of spaces in print 
Python :: pytube3 
Python :: sphinx themes 
Python :: python 3.5 release date 
Python :: coding 
Python :: how to convert .py into .exe through pytohn scripts 
Python :: how to check if string ends with specific characters in python 
Python :: time complexity of data structures in python 
Python :: get status code python 
Python :: Math Module radians() Function in python 
Python :: python loop function 
Python :: shebang line python 
Python :: get current scene file name godot 
Python :: planet earth minecraft 
Python :: how to make a ip tracker in python 
Python :: how to count categories in a csv command line 
Python :: convert code c++ to python online 
Python :: no such column: paintshop_ourservice.date_Created 
Shell :: install git on amazon linux 
Shell :: stop apache server 
Shell :: update google chrome command ubuntu 
Shell :: ubuntu restart mariadb 
Shell :: how to open xampp control panel in ubuntu 
Shell :: remove remote origin 
Shell :: how pip install on centos 
Shell :: ubuntu 14 apache2 graceful restart 
ADD CONTENT
Topic
Content
Source link
Name
7+6 =