List operations and Slices in Python

 

List operations and Slices in Python

List operations and Slices in Python

The + operator is used to concatenate the two lists.

The + operator takes two operands. If both the operands are numeric values then the + acts as the usual addition operator. If one or both the operands are strings, then the + operator acts as string concatenation. If bot the operands are lists, then the + operator acts list concatenation.

a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c)

Output

[1, 2, 3, 4, 5, 6]
#List Operation "+"
l1 = [10, 20, 30]
l2 = [40, 50, 60]
l3 = l1 + l2
l4 = ['VTU', 'BGM'] + l1
l5 = l1 + ['VTU', 'BGM']
l6 = [10, 20, 30] + ['VTU', 'BGM']
print (l3)
print (l4)
print (l5)
print (l6)

Output

[10, 20, 30, 40, 50, 60]
['VTU', 'BGM', 10, 20, 30]
[10, 20, 30, 'VTU', 'BGM']
[10, 20, 30, 'VTU', 'BGM']

Similarly, the * operator repeats a list a given number of times:

[0] * 4

Output

[0, 0, 0, 0]
# Another Example
[1, 2, 3] * 3

Output

[1, 2, 3, 1, 2, 3, 1, 2, 3]

A simple program to demonstrate the list operation * 

The * takes two operands. If both the operands are numeric values then the * operator acts as the usual multiplication operator. If the first operator is a list and the second is an integer number then, the list element is repeated by the number of times the second operator.

l1 = [10, 20, 30]
print ("Before * Operation", l1)
l1 = l1 * 2
print ("After * Operation", l1)

Output

Before * Operation [10, 20, 30]
After * Operation [10, 20, 30, 10, 20, 30]

List slices

The slice operator is used to extract the elements of the list.

The : is the slice operator. The following fragment of code demonstrates the slice operator on the list in python.

Program to demonstrate the List scilce on list in python

#List Slicing 
t = ['a', 'b', 'c', 'd', 'e', 'f']
print(t[:4])
print(t[2:])
print(t[2:5])

Output

['a', 'b', 'c', 'd']
['c', 'd', 'e', 'f']
['c', 'd', 'e']

Program to demnstrate the modification of list elements using scilce operator in python

t = ['a', 'b', 'c', 'd', 'e', 'f']
print ("Before modification", t)
t[1:5] = ['w','x', 'y', 'z']
print ("After modification", t)

Output

Before modification ['a', 'b', 'c', 'd', 'e', 'f']
After modification ['a', 'w', 'x', 'y', 'z', 'f']

Summary:

This tutorial discusses the usage of List operations and Slices in Python. If you like the tutorial do share it with your friends. Like the Facebook page for regular updates and YouTube channel for video tutorials.

Leave a Comment

Your email address will not be published. Required fields are marked *