Slice_operatorUnit5Python
Slice_operatorUnit5Python
What Is an Index?
An index is a position of an individual character or element in a list, tuple, or string. The index
value always starts at zero and ends at one less than the number of items.
Negative indexes enable users to index a list, tuple, or other indexable containers from the end of
the container, rather than the start.
List slicing is the process of accessing a specified portion or subset of a list for some action while
leaving the rest of the list alone. Let us consider a Python list. To access a range of elements in a
list, you must slice it. One method is to utilize the simple slicing operator, i.e. colon (:) With this
operator, one can define where to begin slicing, and where to terminate slicing, and the step. List
slicing creates a new list from an old one.
Syntax
where,
start – index position from where the slicing will start in a list
stop – index position till which the slicing will end in a list
step – number of steps, i.e. the start index is changed after every n steps, and list slicing is
performed on that index
Note – In Python, indexing starts from 0, and not 1.
Get all the Items from One Position to Another Position
Example:
my_list = [1, 3, 5, 7, 9, 11, 13, 15]
print('Items in List from 1st to 6th index are:', my_list[1:6])
Output
Items in List from 1st to 6th index are: [3, 5, 7, 9, 11]
If you wish to display all the elements between two specific indices, put them before and after the
‘:’ symbol. In the preceding example, my list[1:6] returns the elements between the first and sixth
positions. The beginning position (i.e. 1) is included, but the finishing position (i.e. 6) is not.
output: [3,4,5,6,7]
1)Create a list in Python of children selected for science quiz with following names- Arjun,
Sonakshi, Vikram, Sandhya, Sonal, Isha, Kartik
Print the whole list
Delete the name “Vikram” from the list
Add the name “Jay” at the end
Remove the item which is at the second position.
print the length of the list
print the elements from second to fourth position using positive indexing
print the elements from position third to fifth using negative indexing