In this post, we will learn about Lists in python. Here we perform the basic operations on a 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.

Master the basics of data analysis in Python. Expand your skillset by learning scientific computing with numpy.

Take the course on Introduction to Python on DataCamp here https://bit.ly/datacamp-intro-to-python

#### 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 an item to the list using
`append()`

function. - Change the 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 :

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
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) |

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

Pingback: Python Dictionary and its operations - Programming in Python