Learn and Learn

Learn And Learn - great place for tutorials, references and how-to

Python Common List Literals and Operations – Examples & Explanation

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.

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.

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.

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.

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.

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.

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.

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.

 

Loading...
LearnAndLearn.com © 2018 - All rights reserved