List
Table of content
List
It is inbuilt data structure which can store heterogeneous data elements.
How to define list
To define list we use [] (Square Brackets).
Access list elements
We can access the data elements within list with index. In the above example
list with index will be.
To access the 0th element we index the list as ls[0], likewise to access 1st
element, ls[1] and 2st element ls[2].
Modify a list element
Note: It is mutable data structure, means we can do changes in the data
elements.
Suppose we want to replace 0th element i.e 1 with 100. So It is
possible.
Nested List
We can have list within list. We can access the list and its individual
elements and modify those values.
List functions
1) list.append(x) : List can dynamically grow. It is not fixed size data
structure. To add element at last we can use append() function.
2) list.extend(iterable) : To add more than one elements use extends(). As
shown in above example append() can add one element at a time.
3) list.insert(i, x) : inserts the element x at an index i using
insert() function. Elements to the right of the inserted element will moved to
right by 1 index.
4) list.remove(x) : removes the element x from list. If that value is not present in list the ValueError Exception is raised.
5) list.pop(i) : removes the element at the index i. If the index is not passed it removes the last element.
6) list.clear() : removes all the elment from list and makes it empty list.
7) list.index(x) : returns the index of element x in the list. If the element
is not present, it gives value Error.
8) list.count(x) : returns occurrence of element x in the list.
9) list.reverse() : reverse the element of the list.
10) list.sort() : sorts the elements of the list.
11) list.copy() : returns a copy of the list.
12) delete statement (del) : deletes the elements from list provided
indices.
13) slicing in a list : we slice a list by providing start and end index. We have additional optional step.
Thank you folks. If you like this Python 3 post, please do checkout my other post
on
Django with Python 3 series