Lists in Python

In the last section, we discussed about strings and the various properties and functions of strings, like how it can be thought of as a collection of various characters just like a list. In other words, the list is an ordered set of values enclosed in square brackets [ ].

An important difference to be noted is that list is mutable, i.e. it's values can be modified.

As it is nothing but a set of values, we can use the index in square brackets [ ] to identify an value belonging to the list.

The values that make up a list are called its elements, and they can be of any type. We can also say that list data type is a container that holds a number of elements in a given order. For accessing an element in the list, indexing is used, which can be called from both forward and backward direction (similar to strings).


Constructing a List

As already explained, the list is a collection of similar type of data. This data can be an integer, a float, a complex number, a string or any legitimate datatype in python. The list is always provided with some name, similar to a variable, and each element is accessed by their index number. Python has both forward and backwards index number, so for each element there exists one positive and one negative number to access that element (discussed in the next topic). While defining a list, we have to enclose each element of the list within square brackets, and each element is separated by commas.

Suppose, if you want to create an empty list (which is possible in case you want to add the elements later in the program or when user gives the input), then you can initialize it by declaring empty square brackets,

>>> myEmptyList = []

For example, list of some integers will be,

>>> myIntegerList = [9, 4, 3, 2, 8]

A list of float values,

>>> myFloatList = [2.0, 9.1, 5.9, 8.123432]

A list of characters,

>>> myCharList = ['p', 'y', 't', 'h', 'o', 'n']

A list of strings,

>>> myStringList = ["Hello", "Python", "Ok done!"]

Live Example →


These were some basic methods to create a list. Now let's try some other methods.


Deriving from another List

Suppose there is an existing list,

>>> myList1 = ['first', 'second', 'third', 'fourth', 'fifth']

And now you want to create a new list which consists some or all the elements of myList1, then you can you do a direct assignment for complete copying of elements or use slicing, and take only some elements.

For complete copying,

>>> myList2 = myList1

Use slicing, for copying only the first three elements,

>>> myList2 = myList1[0:3]

Live Example →

For copying last three elements,

>>> myList2 = myList1[-4:-1]

Adding Serial Numbers in a List

Suppose you want to add serial whole numbers (i.e., 0, 1, 2, 3, ...) into your list and just don't want to write all of them one by one, do not worry, there is a shortcut for doing this.

For storing 0 to (n-1) numbers in a list use range(n) function.

>>> myList1 = range(9)

This will create a list with numbers 0 to 8 inside it.

>>> myList1 = range(5, 9)

Live Example →

This will create a list having numbers 5, 6, 7, 8 i.e., argument's first number to the (argument's last number - 1).

This range() function can be used for various usecases.

Suppose you want to create a list with squares of all whole numbers. Although there exists various programming approaches for this problem but here is a one line method in python. We will be introducing something new, so it can get a little tricky.

>>> myQuickList = [x**2 for x in range(5)]

The final list will contain elements like [0, 1, 4, 9, 16], i.e. x**2 where x is varying from 0 to (5-1).

for is the keyword here that you may not be familiar with. for is one of the keywords that makes programming do a lot of mundane and redundant task for a programmer, for example, it can create loops of execution. Although there will be a whole chapter dedicated to this, the important thing to note here is that for is the keyword which is responsible for iterating (or repeating) x in range 0 to 4 and finally storing the iterated value's square i.e. (x2) in the list.


Appending to a List

Appending basically means adding to the existing. If you remember we told you how you can create an empty list in python by just declaring an empty square bracket. Now, what to do when you actually have to insert some elements inside the list? This is where append function comes in use. You can add any number of elements to the end of the list in one line without any hassle.

>>> emptyList = []
>>> emptyList.append('The Big Bang Theory')
>>> emptyList.append('F.R.I.E.N.D.S')
>>> emptyList.append('How I Met Your Mother')
>>> emptyList.append('Seinfeld')

Live Example →

So, that will basically create a list of some of the best sitcoms (and isn't empty anymore). If you print the list.

>>>print emptyList

['The Big Bang Theory', 'F.R.I.E.N.D.S', 'How I Met Your Mother', 'Seinfeld']


Indexing of elements

We have already covered about using index to access the sequence of characters in a string in the string tutorial. Similarly, in python, index numbers can be used to access the elements of a list too. Let's create a list of strings and try to access individual strings using index numbers. Here is an example,

>>> fruitsList = ["Orange", "Mango", "Banana", "Cherry", "Blackberry", "Avocado", "Apple"]

As you can see in the code above, we have a list with 7 elements. To find the number of elements in a list, us the function len just like for strings.

>>> len(fruitsList)

7

Live Example →

For every element in the list, following are the index numbers that we should use: (try to understand how we assigned the index numbers.)

ElementForward indexBackward index
Orange0-7
Mango1-6
Banana2-5
Cherry3-4
Blackberry4-3
Avocado5-2
Apple6-1