-
Notifications
You must be signed in to change notification settings - Fork 1
List in Python
he most basic data structure in Python is the sequence. Each element of a sequence is assigned a number – its position or index. The first index is zero, the second index is one, and so forth.
Python has six built-in types of sequences, but the most common ones are lists and tuples
Types — str, unicode, list, tuple, buffer, xrange
There are certain things you can do with all sequence types. These operations include indexing, slicing, adding, multiplying, and checking for membership. In addition, Python has built-in functions for finding the length of a sequence and for finding its largest and smallest elements.
lists are created using [ and ]
li = [1,2,3,4]
accessing list values: list[index]
li0 for first element.
updating the list:
li2 = 3
deleting list:
del li3 – to delete 4th element.
del li – to delete list
Basic list operations:
: [1,2,3][4,3,2] o/p [1,2,3,4,3,2]
- : repeat [1,2]*3 = [1,2,1,2,1,2]
len(li) : length of a list
2 in [1,2,3,4,4] : members in the list
iteration : for x in li print(x)
Built-in List Functions & Methods
Python includes the following list functions −
Sr.No. Function with Description
1 cmp(list1, list2) : Compares elements of both lists.
2 len(list): Gives the total length of the list.
3 max(list): Returns item from the list with max value.
4 min(list): Returns item from the list with min value.
5 list(seq): Converts a tuple into list.
Python includes following list methods
Sr.No. Methods with Description
1 list.append(obj)
Appends object obj to list
2 list.count(obj)
Returns count of how many times obj occurs in list
3 list.extend(seq)
Appends the contents of seq to list
4 list.index(obj)
Returns the lowest index in list that obj appears
5 list.insert(index, obj)
Inserts object obj into list at offset index
6 list.pop(obj=list[-1])
Removes and returns last object or obj from list
7 list.remove(obj)
Removes object obj from list
8 list.reverse()
Reverses objects of list in place
9 list.sort([func])
Sorts objects of list, use compare func if given