Monday 4 April 2022

P#20 Slicing

SLICING

Slicing is the extraction of a part of a string, list, or tuple. It enables users to access the specific range of elements by mentioning their indices. 

We should understand index. Then only slicing will be easier.

 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.

#slice list

aList = [10,20,30, 40, 50]
slc = slice(1,4) # note slice method
print(aList[slc]) #[20, 30, 40]

# slice Tuple

Slicing on Tuple.

aTuple = (10,20,30, 40, 50)
slc = slice(1,4) # note slice method
print(aTuple[slc]) # (20, 30, 40)
# stepping
aList = [10,20,30, 40, 50,60, 70, 80, 90]
stepList = slice(1,8,2)
print(aList[stepList]) # [20, 40, 60, 80]

#Insertion @ Start
aList = [10,20,30, 40, 50,60, 70, 80, 90]
iList = ['a','b','c','d']
aList[:0] = iList
print(aList) # ['a', 'b', 'c', 'd', 10, 20, 30, 40, 50, 60, 70, 80, 90]

#Insertion @ End
aList = [10,20,30, 40, 50,60, 70, 80, 90]
iList = ['a','b','c','d']
aList[len(aList):] = iList
print(aList) # [10, 20, 30, 40, 50, 60, 70, 80, 90, 'a', 'b', 'c', 'd']
alist = "AMET ODL LEARNING"
print(alist[::-1]) # Reverse as string #GNINRAEL LDO TEMA

alist = "AMET ODL LEARNING"

print(alist[4:8]) # returns 4 to 7th characters in the string # ODL
print(alist[0:4]) # from 1 to 4 {4 exclusive} # AMET
print(alist[9::]) # From 10 to last character #LEARNING
print(alist[:8]) # From begining to 8th position #AMET ODL
print(alist[-1]) # last character G
See the above uses of indexing in slicing. Interestingly, it works even for negative indexing.  
Deleting an element

aList.remove(10)

print(aList) # [20, 30, 40, 50, 60, 70, 80, 90, 'a', 'b', 'c', 'd']

Happy Learning at AMET ODL!👌👪



No comments:

Post a Comment

Making Prompts for Profile Web Site

  Prompt: Can you create prompt to craft better draft in a given topic. Response: Sure! Could you please specify the topic for which you...