Python Programming – Some List Operations

In this Page, We are Providing Python Programming – Some List Operations. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Some List Operations

Some list operations

Some of the list operations supported by Python are given below.

Concatenation

List concatenation can be carried out using the + operator.

>>> [ 1 , 2 , 3 ] +[ ' hi ' , ' hello ' ]
[ 1 , 2 , 3 , ' hi ' , ' hello ' ] ;

Repetition

The * operator can be used to carry out repetition operations.

>>> [ ' Hey ' ] *3 
[ ' Hey ' , ' Hey ' , ' Hey ' ]

Membership operation

The list also supports membership operation i.e. checking the existence of an element in a list.

>>> 4 in [ 6 , 8 , 1 , 3 , 5 , 0 ]
False 
>>> 1 in [ 6 , 8 , 1 , 3 , 5 , 0 ]
True

Slicing operation

As list is a sequence, so indexing and slicing work the same way for list as they do for strings. All slice operations return a new list containing the requested elements:

>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> a [ 2 ] 
100
>>> a [ -2 ]
100
>>> a [ 1 : 3 ] 
[ ' eggs ' , 100 ]
>>> a [ : ]
[ ' spam ' , ' eggs ' , 100 , 1234 ]

List slicing can be in form of steps, the operation s [ i: j: k ] slices the list s from i to j with step k.

>>> squares=[ x**2 for x in range ( 10 ) ] 
>>> squares
[ 0 , 1 , 4 , 9 , 16 , 25 , 36 , 49 , 64 , 81 , 100 , 121 , 144 , 169 , 196 ]
>>> squares [ 2 : 12 : 3 ]
[ 4 , 25 , 64 , 121 ]

Slice indices have useful defaults, an omitted first index defaults to zero, an omitted second index defaults to the size of the list being sliced.

>>> squares= [ x**2 for x in range ( 10 ) ]
>>> squares 
[0 , 1 , 4 , 9 , 16 , 25 , 36 , 49 , 64 , 81 , 100 , 121 , 144 , 169 , 196 ]
>>> squares [ 5 : ]
[ 25 , 36 , 49 , 64 , 81 , 100 , 121 , 144 , 169 , 196 ]
>>> squares [ : 5 ]
[ 0 , 1 , 4 , 9 , 16 ]