Lists

In Python, a list is a data type (its documentation is available here, https://docs.python.org/3.4/tutorial/datastructures.html#) that could be used to store elements in a sequence.

The topics discussed in this chapter can be difficult to grasp unless used in practice. Any example that is represented using this notation: >>> indicates that it could be tested using the Python interpreter.

A list may consist of strings, objects (discussed in detail in this chapter) or numbers, and so on. For instance, the following are examples of lists:

    >>> sequence = [1, 2, 3, 4, 5, 6]
>>> example_list = ['apple', 'orange', 1.0, 2.0, 3]

In the preceding set of examples, the sequence list consists of numbers between 1 and 6 while the example_list list consists of a combination of strings, integer, and floating-point numbers. A list is represented by square brackets ([]). Items can be added to a list separated by commas:

    >>> type(sequence)
<class 'list'>

Since a list is an ordered sequence of elements, the elements of a list could be fetched by iterating through the list elements using a for loop as follows:

for item in sequence: 
print("The number is ", item)

The output is something as follows:

    The number is  1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6

Since Python's loop can iterate through a sequence of elements, it fetches each element and assigns it to item. This item is printed on the console.