python list

Python List

Python list is very flexible data structure in python. List can contain element of different types.

How to create list:
Python list is created by using square bracket ‘[]’ >>> my_list = []

The above list is blank, means there is no element present in it. list can be created with element also

>> my_list = [1, "ball", 2.5, "hello world", "cat"]
>>> my_list
[1, 'ball', 2.5, 'hello world', 'cat'] How to access list element:
you can access the list element by indexing. The indexing in python starts from zero to n-1 where n is total number of element in list. so in our list we have index -> 0,1,2,3,4>> my_list[0]
1
>>> my_list[3]
'hello world'

We must provide the available index otherwise IndexError: list index out of range exception will be raised.>>> my_list[5]
Traceback (most recent call last):
File "", line 1, in
IndexError: list index out of range

Negative index
As index in python starts from 0 to n-1 where as negative index starts from -1 to -n.

List slicing
One can extract a part of list using slicing. list[start:end] will return a new list containing the element with the start index till end-1 index. see the example to understand.>>> my_list
[1, 'ball', 2.5, 'hello world', 'cat']

>>> my_list[1:4]
['ball', 2.5, 'hello world']

#you don't have to provide start index when you including the 1st element.
>>> my_list[:3]
[1, 'ball', 2.5]

How to add or change element to list
Adding element to list we can use append, extend or insert method.# append put the element at the end of list.
>>> my_list.append("apple")
>>> my_list
[1, 'ball', 2.5, 'hello world', 'cat', 'apple']

Delete or remove element from list
We can delete one or more items from a list using the keyword del. It can even delete the list entirely.my_list = [1, 'ball', 2.5, 'hello world', 'cat']
>>> del my_list[0]
>>> my_list
['ball', 2.5, 'hello world', 'cat']

We can use remove() method to remove the given item or pop() method to remove an item at the given index.
The pop() method removes and returns the last item if index is not provided. This helps us implement lists as stacks (first in, last out data structure).
We can also use the clear() method to empty a list