Python Programming - List Operations

You can learn about List Manipulation in Python Programs with Outputs helped you to understand the language better.

Python Programming – List Operations

There are several operations that are applicable to lists. These are discussed in the following sections:

Joining Lists

Joining list means to concatenate (add) two lists together. The plus (+) operator, applied to two lists, produces a new list that is a combination of them:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print(c)
[1, 2, 3, 4, 5, 6]
The + operator when used with lists requires both the operands to be of list type, other wise it will produce error. For example,
>>> li = [10, 20 ,30]
>>> li + 2
TypeError: can only concatenate list
(not “int”) to list
>>> li + “xyz”
TypeError: can only concatenate list
(not “str”) to list

Repeating Lists

Multiplying a list by an integer n creates a new list that repeats the original list n times. The * operator repeats a list the given number of times.
>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
The first example repeats [0] four times. The second example repeats the list [1, 2, 3] three times.

Slicing Lists

The slice operator also works on lists. If you omit the first index, the slice starts at the beginning. If you omit the second, the slice goes to the end. So if you omit both, the slice is a copy of the whole list.
>>> t = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
>>> t[1:3]
[‘b’, ‘c’]
>>> t [:4]
[‘a’, ‘ b’ , ‘ c’, ‘ d’ ] ‘
>>> t[3:]
[‘d’, ‘e’, ‘f’]
>>> t [:]
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]

The slice operator on the left side of an assignment operator can modify multiple elements:
>>> t = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
>>> t [1:3] = [‘x’, ‘y’]
>>> print(t)
[‘ a’ , ‘ x’ , ‘ y’ , ‘ d’ , ‘ e ‘ , ‘ f ‘ ]

  • List slicing leads to an extracted part of a list because a list slice is a list in itself.

Comparing Lists

You can test whether the contents of two or more lists are the same or not. The comparison operators can be used to compare lists.
>>> [11, 22] == [11, 22]
True
>>> [11, 22] < [11, 33]
True

Let’s Try

Find and write the output of the following Python codes:

for i in [ 1 , 2 , 3 , 4 ] [ : : -1 ] :
print (i)
>>> [ 21 , 22 ] = = [ 21 , 22 ]
>>> [ 21 , 42 ] > [ 21 , 33 ]

Leave a Reply

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