Lists in Python

Lists in Python

Python has a very versatile data type available that are lists. Lists can be written as comma separated values inside square brackets. As in many other languages python lists can not be of same data type e.g integers or string or floating points.

Suppose following code to

create a list.

To access the list elements (List item start from 0 index)

To print a range of characters in a list

How to change values in list

append method can be used to add  more values to a list.

Delete List Item

For deleting an element from a list we can use del method or remove method, right now we discuss del method.

So result would be.

Important List Operations

Python Expression Results Description
len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
[‘Hi!’] * 4 [‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’] Repetition
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]: print x, 1 2 3 Iteration

Indexing, Slicing, and Matrixes

Because lists are sequences, indexing and slicing work the same way for lists as they do for strings.

Python Expression Results Description
valuelist[2] ‘VALUE!’ Offsets start at zero
valuelist[-2] ‘Value’ Negative: count from the right
valuelist[1:] [‘Value’, ‘VALUE!’] Slicing fetches sections

List  Functions and Methods

SN 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

# Methods ad their 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

In next article we would look Python in more depth. Please eave your comments