Python – Lists

1. Format of Lists

A list is an ordered collection that allows you to add and remove elements at any time.

Each element in a list is assigned a number – its position, or index, with the first index being 0, the second index being 1, and so on.

list1 = ['physics', 'chemistry', 1997, 2000]list2 = [1, 2, 3, 4, 5 ]list3 = ["a", "b", "c", "d"]
print("list1[0]: {}".format(list1[0]))      # Access
print("list2[1:5]: {}".format(list2[1:5]))  # Slice
print("list3: {}".format(list3.append("e"))) # Use append() to add an element

The output of the above example is:

list1[0]:  physicslist2[1:5]:  [2, 3, 4, 5]list3: ["a", "b", "c", "d", "e"]

2. List Operators

The operators + and * for lists are similar to those for strings. The + operator is used to concatenate lists, while the * operator is used to repeat lists.

As shown below:

Python Expression

Result

Description

len([1, 2, 3])

3

Count of elements

[1, 2, 3] + [4, 5, 6]

[1, 2, 3, 4, 5, 6]

Concatenation

[‘Hi!’] * 4

[‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’]

Replication

3 in [1, 2, 3]

True

Check if an element exists in the list

[1, 2, 3, 4, 5, 6][:3]

[1,2,3]

Slicing

for x in [1, 2, 3]: print x,

1 2 3

Iteration

3. Common List Operations

Python - Lists

Common methods:

Method

Description

len(list)

Count of list elements

max(list)

Return the maximum value in the list

min(list)

Return the minimum value in the list

list(seq)

Convert a tuple to a list

list.append(obj)

Add a new object to the end of the list

list.count(obj)

Count occurrences of an element in the list

list.extend(seq)

Add multiple values from another sequence to the end of the list (extend the original list)

list.index(obj)

Find the index of the first occurrence of a value in the list

list.insert(index, obj)

Insert an object into the list

list.pop([index=-1])

Remove an element from the list (default is the last element) and return its value

list.remove(obj)

Remove the first occurrence of a value from the list

list.reverse()

Reverse the elements in the list

list.sort(cmp=None, key=None, reverse=False)

Sort the original list

4. Traversing Lists

#!/usr/bin/env python
# -*- coding: utf-8 -*-
if __name__ == '__main__':    list = ['html', 'js', 'css', 'python']
    # Method 1    print 'Traversing list method 1:'    for i in list:        print ("Index: %s   Value: %s" % (list.index(i) + 1, i))
    print '
Traversing list method 2:'
    # Method 2    for i in range(len(list)):        print ("Index: %s   Value: %s" % (i + 1, list[i]))
    # Method 3    print '
Traversing list method 3:'    for i, val in enumerate(list):        print ("Index: %s   Value: %s" % (i + 1, val))
    # Method 3    print '
Traversing list method 3 (setting initial position, only changing the starting index):'    for i, val in enumerate(list, 2):        print ("Index: %s   Value: %s" % (i + 1, val))

Leave a Comment