Slicing a list in Python is a kind of operation that returns part of a list. The basic form of a slice is using starting and ending index with colon between of a list inside square brackets following a list. Say we have a list for family member, and will get part of a list from 2nd to 4th element.
#create a list of family members
familymember = ["Wilson", "Shirley", "Mico","Dudu","Miaomiao","Maomao", "Mia"]
#show the elements of whole list
familymember
#output
['Wilson', 'Shirley', 'Mico', 'Dudu', 'Miaomiao', 'Maomao', 'Mia']
#slice of list, return 2nd to 4th elements
family_2_4 = familymember[2:5]
family_2_4
#output
['Mico', 'Dudu', 'Miaomiao']
We see that element with ending index is not included in the slicing object. And either or both of ending and starting index can be omitted in slicing.
#omit ending index, and all the elements from 2nd will be returned
family2end= familymember[2:]
family2end
#output
['Mico', 'Dudu', 'Miaomiao', 'Maomao', 'Mia']
#omit starting index, all the elements up to 3rd are returned
family4start = familymember[:4]
family4start
#output
['Wilson', 'Shirley', 'Mico', 'Dudu']
#omit both starting and ending index, a copy of list returned
familycopy = familymember[:]
familycopy
#output
['Wilson', 'Shirley', 'Mico', 'Dudu', 'Miaomiao', 'Maomao', 'Mia']
Python uses minus symbol for counting a list from end.
#the last element of list returned
familymember[-1]
#output
'Mia'
#slicing from beginning to the 3nd element from the ending
familymember[:-3]
#output
['Wilson', 'Shirley', 'Mico', 'Dudu']
#slicing from 3nd element from ending to end of list
familymember[-3:]
#output
['Miaomiao', 'Maomao', 'Mia']
Click here to download Python Course Source Files !
For online Python training registration, click here ! Pandas provides flexible ways of generating data…
For online Python training registration, click here ! Data frame is the tabular data object…
Click her for course registration ! When a data frame in Python is created via…
We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…