xxxxxxxxxx
# a list of strings
mylist = ['one', 'two', 'three']
mytuple = ('four', 'five', 'six')
#add the tuple elements to the list
mylist.extend(mytuple)
print(mylist)
xxxxxxxxxx
# Way 1
list1 + list2
# Way 2
list1.extend(list2)
# Way 3
list1.append(list2[:])
# Way 4
list1.append(*list2)
xxxxxxxxxx
#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]
xxxxxxxxxx
Difference between List append() and List extend() method
a =[1,2]
b= [3,4]
# append() method
a.append(b)
print("Using append() method", a)
x =[1,2]
y= [3,4]
# extend() method
x.extend(y)
print("Using extend() method", x)
xxxxxxxxxx
# a list of strings
mylist = ['one', 'two', 'three']
mytuple = ('four', 'five', 'six')
#add the tuple elements to the list
mylist.extend(mytuple)
print(mylist)
xxxxxxxxxx
animals = ['dog', 'cat']
# tuple
mammals = ('tiger', 'elephant')
animals.extend(mammals)
print('Updated list:', animals)
# dictionary
birds = {'owl': 1, 'parrot': 2}
animals.extend(birds)
print('Updated list:', animals)
#Updated list: ['dog', 'cat', 'tiger', 'elephant']
#Updated list: ['dog', 'cat', 'tiger', 'elephant', 'owl', 'parrot']
xxxxxxxxxx
# My List
my_list = ['geeks', 'for', 'geeks']
# My Tuple
my_tuple = ('DSA', 'Java')
# My Set
my_set = {'Flutter', 'Android'}
# Append tuple to the list
my_list.extend(my_tuple)
print(my_list)
# Append set to the list
my_list.extend(my_set)
print(my_list)
['geeks', 'for', 'geeks', 'DSA', 'Java']
['geeks', 'for', 'geeks', 'DSA', 'Java', 'Android', 'Flutter']
xxxxxxxxxx
1
2
3
4
fruits = ["apple", "banana", "orange"]
more_fruits = ["mango", "grape"]
fruits.extend(more_fruits)
print(fruits)
Copied!