Python Lists – Add, Append, Modify, Remove, Slice

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.

Program on Github

Python Lists- Code Visualization

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, similarly lst[m:] removes all elements from m to end and lst[m:n] = [] removes all elements from m to n.
  • The whole list can be removed by lst[:] = []

Program on Github

Program :

Output :

List operations - programminginpython
List operations – programminginpython.com

Program on Github

2 Comments

  1. Pingback: Python tuple operations - Add, Remove, Slice, Concatenate, Reverse

  2. Pingback: Python Dictionary and its operations - Programming in Python

Leave a Reply