rdatacode provide affordable online training course for Python and R programming at fundamental level, click here for more details.

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']

You can also watch videos on our YouTube channel for more understanding of Python programming skills.


0 Comments

Leave a Reply

Avatar placeholder