Extending a list in Python (5 different ways)


Lists are the most frequently used data structures of python. When we want to add more elements to a list, the extension of list happens. This can be done in following 5 different ways.

Using the Plus operator

Here we simply add the elements of a new list using the + operator. The behavior is similar to how we modify the values of a variable.

Examples

list = ['Mon','Tue','Wed']
list = list + ['Thu','Fri']
print(list)

Output

Running the above code gives us the following result −

['Mon', 'Tue', 'Wed', 'Thu', 'Fri']

Using Slicing

We can use slicing to add elements at the end of a list. Here we take the len() function to estimate the length of the list then slice it from the end and assign values from a new list.

Examples

list = ['Mon','Tue','Wed']
list[len(list):] = ['Thu','Fri']
print(list)

Output

Running the above code gives us the following result −

['Mon', 'Tue', 'Wed', 'Thu', 'Fri']

Using append()

We can append elements at the end of the list using appen() function. We can append one element at a time or we can append another list which remains as a list even after appending.

Examples

list = ['Mon','Tue','Wed']
list.append('Thu')
list.append('Fri')
list.append(['sat','sun'])
print(list)

Output

Running the above code gives us the following result −

['Mon', 'Tue', 'Wed', 'Thu', 'Fri', ['sat', 'sun']]

Using Extend

extend() is a similar function to append where elements are added to a list. But unlike append(), we can add another list and the new elements added do not appear as a list inside a list.

Examples

list1 = ['Mon','Tue','Wed']
list2 = ['Thu','Fri','Sat']
list1.extend(list2)
print(list1)

Output

Running the above code gives us the following result −

['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']

Using chain()

We can use the chain() from the library itertools which concatenates multiple lists together. Here we can have more than two lists getting concatenated and finally all elements belong to one final list.

Examples

from itertools import chain
list1 = ['Mon','Tue','Wed']
list2 = ['Thu','Fri']
list3 = ['Sat','Sun']
list4 = (list(chain(list1, list2,list3)))
print(list4)

Output

Running the above code gives us the following result −

['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
raja
Published on 07-Aug-2019 08:38:07
Advertisements