5 List Operations in Python

5 must-know list operations in Python.

You are at the right place to learn further about list operations and their uses.

So, let's jump into our topic- list operations of Python.

image

List Operations in Python

It is the computation or actions applied to the variable containing the list of data types in an expression.

List manipulation in Python can be done using various operators like concatenation (+), repetition (*), slicing of the list, and membership operators( in /not in). So, Let's understand each operator in brief.

1. Concatenation operator (+)

2. Repetition operator (*)

3. List Slicing in Python

4. Comparison Operator

5. Membership Operator (in, not in)

1. Concatenation operator (+)

The (+) operator is used to add to two lists.

The syntax of the given operation is: List1+List2

>>>lst1=[12, 34, 56]
>>>lst2=[78, 90]
>>>print(lst1+lst2)

#Output
[12, 34, 56, 78, 90]

2. Repetition operator (*)

Like string, (*) operator replicates the string number of specified times.

The syntax of the given operation: List*n

>>>lst1=[12, 34, 56]
>>>print( lst1*3)

>#Output
[12, 34, 56, 12, 34, 56, 12, 34, 56]

3. List Slicing in Python

List slicing returns a slice or part of the list from the given index range x to y. (x is included but y is not included).

The syntax of the list slicing is: List[ start: stop]

>>>lst1= [12, 34, 56, 78, 90]
>>>x= lst1[1: 4]
>>>print(x)

#Output
[34, 56, 78]

4. Comparison Operator

Python offers standard comparison operators like <, >, ==, != to compare two lists.

For comparison, two lists must-have elements of comparable data types, otherwise, you will get an error.

Python gives the result of comparison operators as True or False and moreover, it compares list element by element it compares the first element if they are the same then will move to the next, and so on.

Comparison: [12, 3, 4 , 0] > [9, 12, 34]

Result: True

Reason: compared the first element of both the list, which is 12 and 9, as 12> 9 hence return True

5. Membership Operator (in, not in)

The membership operator checks whether an element exists in the given list.

  • in: Return True if an element exists in the given list; False otherwise

  • not in: Return True if an element does not exist in the given list; False otherwise.

    >>>lst1=[12, 34, 56, 78, 90]
    >>>56 in lst1
    >>>12 not in lst1
    
    #Output
    True
    False
    

Conclusion

At last, In conclusion, Python offers various operators to enhance their performance. Hence, make list programming easier. List operations in Python are simple but very beneficial for coding. To get a better knowledge of lists in Python also learn list methods and list functions.

Hope you will try it by yourself!

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics