Concatenation of a list in Python with Example
In Python, we can add two or more lists. The addition is basically the merging of items of different lists into one list. This process is called concatenation of list in Python Programming Language.
1 2 3 4 5 | list1 = [1,2,3] list2 = [4,5,6] list3 = list1 + list2 print(list3) |
Output:
[1, 2, 3, 4, 5, 6]
In the above example, we concatenate list1 and list2 into a list3. The items of the second list are added at the end. Now we concatenate more than two lists.
1 2 3 4 5 6 7 | list1 = [1,2,3] list2 = [4,5,6] list3 = [7,8,9,10] list4 = ['a','b','c','d'] list5 = list1 + list2 + list3 + list4 print(list5) |
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'a', 'b', 'c', 'd']
Subtract or Deduct list from other lists in Python with Example
Subtraction or deduction of a list from other list is not allowed in Python programming language. TypeError
will occur if we do this.
1 2 3 4 5 | list1 = [1,2,3,4] list2 = [4,5,6] list3 = list1 - list2 print(list3) |
Output:
TypeError: unsupported operand type(s) for -: 'list' and 'list'
Repeat items of list in Python with Example
To repeat items of the list, we use multiplication operator ‘*’ with a number that tells how many time a list items be repeated.
1 2 3 4 5 6 | list1 = [1,2,3,4] repeatList2 = list1 * 2 repeatList5 = list1 * 5 print('List item is repeated for 2 times',repeatList2 ) print('List item is repeated for 5 times',repeatList5 ) |
Output:
('List item is repeated for 2 times', [1, 2, 3, 4, 1, 2, 3, 4])
('List item is repeated for 5 times', [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
Iteration by using list items in Python with Example
For loop is used to iterate list items. To output all items of the list we can use for loop. Look at the following example.
1 2 3 | list1 = [1,2,3,4,5] for y in list1: print(y) |
Output:
1
2
3
4
5
Check membership of an item in a list in Python
To check whether a particular item is a member or an item of a list or not, we use in
operator.
1 2 3 4 5 6 7 | # If something is not a member of the list. list1 = [1,2,3,4,5] if 3 in list1: print('This is a member of a list') else: print('This is not the member of the list') |
Output:
This is a member of a list
In the above example 3 in list1
is a logical expression.
Let’s take another example where something is not the member of the list.
1 2 3 4 5 6 | # If something is not a member of the list. list1 = [1,2,3,4,5] if 7 in list1: print('This is a member of a list') else: print('This is not the member of the list') |
Output:
This is not the member of the list
How to add single item at the end of the list in Python
We use append()
method of list to add an item to the list in Python. You can read in detail in this “Difference Between append() and extend() Method in Python” and “What is List in Python Programming Language” articles.