List Extend – Append a list to another list in python

Spread the love

List Extend –

The extend method add all the elements of a list ( or any iterable ) to the end of the current list.

Syntax of List Extend –

list.extend(iterable)

Append a list to the end of another list –

In [1]: companies = ['Google','Apple','Amazon']

In [2]: more_companies = ['Microsoft','Facebook']

In [3]: companies.extend(more_companies)

In [4]: companies
Out[4]: ['Google', 'Apple', 'Amazon', 'Microsoft', 'Facebook']

Add elements of a tuple or set to a list –

In [6]: companies = ['Google','Apple']

In [7]: comapnies_tuple = ('Amazon','Microsoft')

In [8]: companies_set = {'Facebook','Netflix'}

In [9]: # add a tuple to a list

In [10]: companies.extend(comapnies_tuple)

In [11]: companies
Out[11]: ['Google', 'Apple', 'Amazon', 'Microsoft']

In [12]: # add a set to a list

In [13]: companies.extend(companies_set)

In [14]: companies
Out[14]: ['Google', 'Apple', 'Amazon', 'Microsoft', 'Netflix', 'Facebook']

Difference between Append and Extend –

In [15]: nums1 = [5, 10, 15]

In [16]: nums2 = [5, 10, 15]

In [17]: nums3 = (20, 25)

In [18]: nums1.extend(nums3)

In [19]: nums1 
Out[19]: [5, 10, 15, 20, 25]

In [20]: nums2.append(nums3)

In [21]: nums2
Out[21]: [5, 10, 15, (20, 25)]

Rating: 1 out of 5.

Leave a Reply