List Slicing & List Operations in python..

List Slicing:

The slicing operator return a subset of list called slice, by specifying start and end indexes.

Syntax:

list_variable_name [start:end]

Creating List without using Constructor:

list1=['ram','shyam',23,45,67,20.05] print(list1[1:4]) print(list1[2:5]) print(list1[:3]) print(list1[:]) print(list1[::-1]) print(list1[2::])

Output:

['shyam', 23, 45] [23, 45, 67] ['ram', 'shyam', 23] ['ram', 'shyam', 23, 45, 67, 20.05] [20.05, 67, 45, 23, 'shyam', 'ram'] [23, 45, 67, 20.05]

List slicing with step-size:

The third parameter step-size is to select list with step-size.

Syntax:

name_of_list_variable [staert:end:step]

Example:

list1=['ram','shyam',23,45,67,20.05] print(list1[0:4:2])

Output:

['ram', 23]

List Operations:

Traversing a List:

To traverse a list we use "for in" statement which make it easy to look over the item in a list.

list1=['ram','shyam',23,45,67,20.05] for var in list1: print(var)

Output:

ram shyam 23 45 67 20.05

If we need both index and item, we use enumerate function.

list1=['ram','shyam',23,45,67,20.05] for var1,var2 in enumerate(list1): print(var1,var2)

Output:

0 ram 1 shyam 2 23 3 45 4 67 5 20.05

If we need only index, we can use range and len function.

list1=['ram','shyam',23,45,67,20.05] for var1 in range(len(list1)): print(var1)

Output:

0 1 2 3 4 5

For shortcut list operations, we use built in Functions

Comments

Popular posts from this blog

Introduction to Python.

Decision Making Statement.