You are on page 1of 5

Reading elements/items from list using slicing

Using index we can read only one element or item from list. Index allows reading
in sequential and random order.
Using slicing we can read more than one element/value from list.
Slicing is done using two approaches.
1. Slice operator
2. Slice object
Slicing always return new list consists of elements from existing list.

Slice operator
Slice operator required 3 values
1. Start index
2. Stop index
3. Step

Syntax: sequence-name[start:stop:step]
Slice operator internally uses range for generating indexes.

Example:
>>> list1=[10,20,30,40,50,60,70,80,90,100]
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list2=list1[::]
>>> print(list2)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list3=list1[::1]
>>> print(list3)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list4=list1[::2]
>>> print(list4)
[10, 30, 50, 70, 90]
>>> list5=list1[::-1]
>>> print(list5)
[100, 90, 80, 70, 60, 50, 40, 30, 20, 10]
>>> list6=list1[::-2]
>>> print(list6)
[100, 80, 60, 40, 20]
>>>

The default start and stop values are taken based on step value.
If step value is +ve the default start is 0 and stop is length of list.
If step value is –ve the default start is -1 and stop is –lengh of list.
Example:
# write a program to read n numbers into list and first m maximum numbers
list1=[]
n=int(input("Enter how many elements?"))
for i in range(n):
ele=int(input("Enter any element"))
list1.append(ele)

m=int(input("Enter how many maximum"))


list1.sort()
list2=list1[-m:]
print(list1)
print(list2)
Output:
Enter how many elements?6
Enter any element1
Enter any element6
Enter any element3
Enter any element7
Enter any element2
Enter any element4
Enter how many maximum3
[1, 2, 3, 4, 6, 7]
[4, 6, 7]
>>>

Slice object
class slice(stop)
class slice(start, stop[, step])
Return a slice object representing the set of indices specified by range(start, stop,
step).

What is difference between slice operator and slice object?


Slice operator is not reusable.
Slice object is reusable.

>>> list1=list(range(10,110,10))
>>> s1=slice(5)
>>> list2=list1[s1]
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> print(list2)
[10, 20, 30, 40, 50]
>>> s2=slice(-1,-5,-1)
>>> list3=list1[s2]
>>> print(list3)
[100, 90, 80, 70]
>>>
What is difference between indexing and slicing?
Index is used to read only one value
Slicing is used to read more than one value
Index required only one value
Slicing required 3 values (start,stop,step)

Iterator
Iterator is a cursor or object which allows to read data from collections.
an object representing a stream of data. Repeated calls to the iterator’s __next__()
method (or passing it to the built-in function next()) return successive items in the
stream.

You might also like