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 :: draw bounding box on image python cv2 
Python :: python print os platform 
Python :: pandas reciprocal 
Python :: How to check how much time elapsed Python 
Python :: python two while loops at same time 
Python :: create text in python if not exists 
Python :: wtf forms required 
Python :: python year month from date 
Python :: python read file without newline 
Python :: pandas standardscaler 
Python :: use beautifulsoup 
Python :: convert dataframe column to float 
Python :: ctrl c selenium python 
Python :: brownie get active network 
Python :: how to get the current web page link in selenium pthon 
Python :: remove column from dataframe 
Python :: pandas read csv without header 
Python :: python first two numbers 
Python :: how to dynamically access class properties in python 
Python :: how to square each term of numpy array python 
Python :: python - save file 
Python :: bs4 from url 
Python :: extract numbers from sklearn classification_report 
Python :: identity matrix in python 
Python :: easy sending email python 
Python :: numpy replicate array 
Python :: python dict to url params 
Python :: how to get pygame window height size 
Python :: mape python 
Python :: resample and replace with mean in python 
ADD CONTENT
Topic
Content
Source link
Name
7+2 =