Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

append vs. extend in list python

#List [], mutalbe

# Difference between List append() and List extend() method
# append() adds an single object to the list
# extend() unpacks the passed object and adds all elements in that object individually to the list

# append() method 
a = [1,2]
b = [3,4]
a.append(b)		#append() adds one element to the list
print("Using append() method", a)	#[1, 2, [3, 4]]

# extend() method
x =[1,2]
y= [3,4]
x.extend(y)		#extend() adds multiple elements
print("Using extend() method", x)	#[1, 2, 3, 4]

sample_list = []
sample_list.extend('abc')       #extend() unpacks the string and pass each char individually
print(sample_list)              #['a', 'b', 'c']

# plus assignment, augmented assignment, concatenate merge the 2 lists, works like extend()
c =[1,2]
d = [3,4]
print(c + d)      #[1, 2, 3, 4]   #concatenate works like extend()
c += d
print("Using augmented assignment method", c)	#[1, 2, 3, 4]
 
PREVIOUS NEXT
Tagged: #append #extend #list #python
ADD COMMENT
Topic
Name
4+9 =