Python Lists — Add, Append, Modify, Remove, Slice
Published in
3 min readJul 28, 2018
In this post, we will learn about Lists in python. Here we perform the basic operations on list like adding items to a list, appending an item at the end of the list, modify the value of the item in the list, removing an item from the list, removing all the items from the list and some slicing operations.
Task :
To perform add, append, modify, remove and slice operations on a list.
Approach :
- Define a list
lst = []
with some sample items in it. - Find the length of the list using
len()
function. - Append a item to the list using
append()
function. - Change value of an item in a list by specifying an index and its value
lst[n] = 'some value'
- Perform slice operation, slice operation syntax is
lst[begin:end]
- Leaving the begin one empty
lst[:m]
gives the list from 0 to m. - Leaving the end one empty
lst[n:]
gives the list from n to end. - Giving both begin and end
lst[n:m]
gives the list from n to m. - An advanced slice operation with 3 options
lst[begin:end:step]
- Leaving both begin and end empty and giving a step of -1,
lst[::-1]
it reverses the whole list. - To remove an element using slice
lst[:n] = []
removes all elements from 0 to n, similarlylst[m:]
removes all elements from m to end andlst[m:n] = []
removes all elements from m to n. - The whole list can be removed by
lst[:] = []
Program :
lst = ['abc', 'def', 'ghi', 'jklm', 'nopqr', 'st', 'uv', 'wxyz', '23', 's98', '123', '87']# prints the length of the list
print('Length of the list is : ', len(lst))# appends an item to the list
lst.append('sdd')
print('\nThe list appended a new element "sdd" at the end \n', lst)# changes the value of an item in a list
lst[0] = 'aaa'
print('\nThe value of the first element in the list is changed to "aaa" \n', lst)# Slicing
# shows only items starting from 0 upto 3
print('\nList showing only items starting from 0 upto 3\n', lst[:3])# shows only items starting from 4 to the end
print('\nList showing only items starting from 4 to the end\n', lst[4:])# shows only items starting from 2 upto 6
print('\nList showing only items starting from 2 upto 6\n', lst[2:6])# reverse all items in the list
print('\nList items reversed \n', lst[::-1])# removing items from list
lst[:1] = []
print('\nFirst element is removed from the list \n', lst)# removing whole list
lst[:] = []
print('\nComplete list removed \n', lst)