A List is an ordered set of values, where each value is identified by an index. The values that make up a list are called it’s elements. Lists are similar to strings, which are ordered sets of characters, except that the elements of a list can have any type, you can put numbers, letters, strings and nested lists all on the same list. Lists and strings and another things that behave like ordered sets are called sequences.

Defining List:

l = []
l = [expression, …]

To create a list, put a number of expressions in square brackets. The expressions can be anything, you can put all kinds of objects in lists, including other lists, and multiple references to a single object.

You can also use the built-in list() function to create lists:

l = list()
l = list(expression)

>>> l = [“apple”, “mango”, “banana”, “melon”, “orange”]
>>> L = [“red”, “blue”, “green”, “white”, “black”]
>>> li = [1, 2, 3, 4, 5]

In above example we have defined three different list consists of elements.

Accessing List Elements:

The syntax for accessing the elements of a list is the same as the syntax for accessing the characters of a string. The bracket operator ( [] not to be confused with an empty list). The expression inside the brackets specifies the index.  len(L) function returns the number of elements in the list, L[i] returns the element at index i (the first elements has index 0), and L[x:y] returns a new list, containing the objects between x and y.

Example:

>>> L = ["red", "blue", "green", "white", "black"]
>>> len(L)
5
>>> L[0]
'red'
>>> L[1]
'blue'
>>> L[2]
'green'
>>> L[3]
'white'
>>> L[4]
'black'
>>> L[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

In above example "L" is list of elements as string, len(L) returns the number of elements in "L" i.e. 5. As we know the first element has index 0, L[0], L[1], L[2], L[3], L[4] returns the respective elements as list “L” is consists of 5 elements, but when you try to access the L[5] it will raise "IndexError" because the list has only 5 elements and we are trying to access 6th element.

We can access list using negative indices as shown in example below;

Example:

>>> L = ["red", "blue", "green", "white", "black"]
>>> L[-5]
'red'
>>> L[-4]
'blue'
>>> L[-3]
'green'
>>> L[-2]
'white'
>>> L[-1]
'black'

List Slicing:

We can get a subset of a list, called a “slice”, by specifying two indices. The return value is a new list containing all the elements of the list, in order, starting with the first slice index, up to second slice index, but not including the second slice index. Slicing works if one or both of the slice indices is negative. Lists are zero-based, so L[0:3] returns the first three elements of the list, starting at L[0], up to but not including L[3].

Example:

>>> L = ["red", "blue", "green", "white", "black"]
>>> L[0:2]
['red', 'blue']
>>> L[0:1]
['red']
>>> L[2:5]
['green', 'white', 'black']
>>> L[2:3]
['green']
>>> L[1:4]
['blue', 'green', 'white']
>>> L[-4:-1]
['blue', 'green', 'white']
>>> L[-5:-4]
['red']

If the left slice index is 0, you can leave it out. So L[:3] is the same as L[0:3].Similarly, if the right slice index is the length of the list, you can leave it out. So L[3:] is the same as L[3:5], because this list has five elements. Note the symmetry here. In this five-element list, L[:3] returns the first 3 elements, and L[3:] returns the last two elements. In fact, L[:n] will always return the first n elements, and L[n:] will return the rest, regardless of the length of the list. If both slice indices are left out, all elements of the list are included. But this is not the same as the original L list; it is a new list that happens to have all the same elements. L[:] is shorthand for making a complete copy of a list. As Shown in example below;

Example:

>>> L = ["red", "blue", "green", "white", "black"]
>>> L[:3]
['red', 'blue', 'green']
>>> L[3:]
['white', 'black']
>>> L[:]
['red', 'blue', 'green', 'white', 'black']

Updating Elements of List:

Instead of many other methods of updating list and adding extra elements to list, we can use list indices to update elements of list. If we want to update "blue" with "purple" and "white" with "yellow" we can do so, as shown in example below; Note: After this operation we will get complete new updated list.

Example:

>>> L = ["red", "blue", "green", "white", "black"]
>>> L[1] = "purple"
>>> L[3] = "yellow"
>>> L
['red', 'purple', 'green', 'yellow', 'black']

Removing Elements from List:

As we can update the elements of list, similarly we can remove the elements from list. If we want to remove "red" and "black" from list we can do so, as shown in example below; Note: After this operation we will get complete new updated list.

Example:

>>> L
['red', 'purple', 'green', 'yellow', 'black']
>>> del L[0]
>>> del L[3]
>>> L
['purple', 'green', 'yellow']

List Operators:

Lists can be concatenated with the + operator. list = list + otherlist. The + operator returns a new (concatenated) list as a value. The * operator works on lists as a repeater. li = [‘a’, ‘b’] * 3 is equivalent to li = [‘a’, ‘b’] + [‘a’, ‘b’] + [‘a’, ‘b’], which concatenates the three lists into one, as shown in example below;

Example:

>>> L1 = ['red', 'purple', 'green']
>>> L2 = ['yellow', 'black']
>>> L = L1 + L2
>>> L
['red', 'purple', 'green', 'yellow', 'black']

>>> L = ['a', 'b']
>>> L * 3
['a', 'b', 'a', 'b', 'a', 'b']

Using 'in' operator we can check presence element is in list, which returns boolean value i.e. True or False. As shown in example below, 'red' is one of the element of list 'L' it returns 'True' and blue is not in list 'L' so it returns 'False'.

Example:

>>> L = ['red', 'purple', 'green', 'yellow', 'black']
>>> 'red' in L
True
>>> 'blue' in L
False
>>> 'black' in L
True
>>> 'orange' in L
False


Nested Lists:

A nested list is a list that appears as an element in another list. In example below, the element with index 2 is a nested list:

Example:

>>> L = ['red', 'purple', ['apple', 'banana', 'orange']]
>>> L
['red', 'purple', ['apple', 'banana', 'orange']]
>>> l = [1, 3, ['James', 'Kim']]
>>> l
[1, 3, ['James', 'Kim']]

To extract an element from the nested list, we can proceed in two steps:

Example:

>>> L = ['red', 'purple', ['apple', 'banana', 'orange']]
>>> Li = L[2]
>>> Li[1]
'banana'
>>> Li[2]
'orange'
>>> Li[0]
'apple'

we can combine above steps:

Example:

>>> L[2][0]
'apple'
>>> L[2][1]
'banana'
>>> L[2][2]
'orange'

Python Builtin Methods for List:

Python has many builtin methods for list which are described below with example. As we have learned in "Python help and dir post", you can find all methods using dir() function. For Example: L = [1, 2, 3] dir(L) will give you builtin methods for list.

cmp() : The method cmp() compares elements of two lists. If elements are of the same type, perform the compare and return the result. If elements are different types, check to see if they are numbers. If numbers, perform numeric coercion if necessary and compare. If either element is a number, then the other element is "larger" (numbers are "smallest"). If either element is a number, then the other element is "larger" (numbers are "smallest"). If we reached the end of one of the lists, the longer list is "larger." If we exhaust both lists and share the same data, the result is a tie, meaning that 0 is returned.

Example:

>>> L = ['red', 'purple', 'green', 'yellow', 'black']
>>> l = ['apple', 'banana', 'orange', 'grape', 'melon']
>>> cmp(L, l)
1
>>> L > l
True
>>> cmp(l, L)
-1
>>> l > L
False

len() : The method len() returns the number of elements in the list.

Example:

>>> L = ['red', 'purple', 'green', 'yellow', 'black']
>>> l = ['apple', 'banana', 'orange']
>>> len(L)
5
>>> len(l)
3

max() : The method max returns the elements from the list with maximum value.

Example:

>>> L = [12, 56, 76, 23, 43, 33]
>>> l = ['apple', 'banana', 'orange']
>>> max(L)
76
>>> max(l)
'orange'

min() : The method min() returns the elements from the list with minimum value.

Example:

>>> L = [12, 56, 76, 23, 43, 33]
>>> l = ['apple', 'banana', 'orange']
>>> min(L)
12
>>> min(l)
'apple'

append() : The method append() appends a passed element into the existing list. This method does not return any value but updates existing list.

Example:

>>> L = [12, 56, 76, 23, 43, 33]
>>> L.append(212)
>>> L
[12, 56, 76, 23, 43, 33, 212]
>>> l = ['apple', 'banana', 'orange']
>>> l.append('melon')
>>> l
['apple', 'banana', 'orange', 'melon']

count() : The method count() returns count of how many times element occurs in list.

Example:

>>> L = [12, 56, 76, 23, 43, 23, 12, 23]
>>> L.count(23)
3
>>> L.count(12)
2
>>> L.count(56)
1
>>> l = ['apple', 'banana', 'orange', 'apple']
>>> l.count('apple')
2

extend() : The method extend() appends the contents of 'l' list to 'L' list.

Example:

>>> L = [12, 56, 76, 23, 43, 33]
>>> l = ['apple', 'banana', 'orange']
>>> L.extend(l)
>>> L
[12, 56, 76, 23, 43, 33, 'apple', 'banana', 'orange']

index() : The method index() returns the lowest index in list that element appears otherwise raise an exception indicating that value does not find.

Example:

>>> L = [12, 56, 76, 23, 43, 33, 'apple', 'banana', 'orange']
>>> L.index(43)
4
>>> L.index('orange')
8
>>> L.index('melon')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'melon' is not in list

insert() : The method insert() inserts element into list at given index.

Example:

>>> L = ['apple', 'banana', 'orange']
>>> L.insert(3, 'melon')
>>> L
['apple', 'banana', 'orange', 'melon']
>>> L.insert(1, 55)
>>> L
['apple', 55, 'banana', 'orange', 'melon']
>>> L.insert(6, 'red')
>>> L
['apple', 55, 'banana', 'orange', 'melon', 'red']

pop() : The method pop() removes and returns last element from the list.

Example:

>>> L = ['apple', 55, 'banana', 'orange', 'melon', 'red']
>>> L.pop()
'red'
>>> L
['apple', 55, 'banana', 'orange', 'melon']
>>> L.pop(1)
55
>>> L
['apple', 'banana', 'orange', 'melon']
>>> L.pop(2)
'orange'
>>> L
['apple', 'banana', 'melon']

remove() : This method does not return any value but removes the given element from the list.

Example:

>>> L = ['apple', 'banana', 'melon', 33, 45, 'apple', 'melon']
>>> L.remove('apple')
>>> L
['banana', 'melon', 33, 45, 'apple', 'melon']
>>> L.remove(45)
>>> L
['banana', 'melon', 33, 'apple', 'melon']
>>> L.remove('melon')
>>> L
['banana', 33, 'apple', 'melon']

reverse() : The method reverse() reverses elements of list in place.

Example:

>>> L = ['banana', 33, 'apple', 'melon']
>>> L.reverse()
>>> L
['melon', 'apple', 33, 'banana']
>>> l = [1, 4, 66, 33, 67, 8]
>>> l.reverse()
>>> l
[8, 67, 33, 66, 4, 1]

sort() : This method does not return any value but sort the elements from the list.

Example:

>>> l = [8, 67, 33, 66, 4, 1]
>>> l.sort()
>>> l
[1, 4, 8, 33, 66, 67]
>>> L = ['red', 'blue', 'yellow', 'purple']
>>> L.sort()
>>> L
['blue', 'purple', 'red', 'yellow']
>>> li = ['z', 'w', 'k', 'a', 'd', 'e', 'y']
>>> li.sort()
>>> li
['a', 'd', 'e', 'k', 'w', 'y', 'z']

When to Use Lists:

  • When you need a mixed collection of data all in one place.
  • When the data needs to be ordered.
  • When your data requires the ability to be changed or extended. Remember, lists are mutable.
  • When you don’t require data to be indexed by a custom value. Lists are numerically indexed and to retrieve an element, you must know it’s numeric position in the list.
  • When you need a stack or a queue. Lists can be easily manipulated by appending/removing elements from the beginning/end of the list.
    When your data doesn’t have to be unique. For that, you would use sets.
The following two tabs change content below.
Mr Surendra Anne is from Vijayawada, Andhra Pradesh, India. He is a Linux/Open source supporter who believes in Hard work, A down to earth person, Likes to share knowledge with others, Loves dogs, Likes photography. He works as Devops Engineer with Taggle systems, an IOT automatic water metering company, Sydney . You can contact him at surendra (@) linuxnix dot com.