Lists in Python With Examples

Spread the love

What is a List in Python?

A list is a collection of items in a particular order. You can put anything inside a list integers, floats, strings or even lists themselves.

Creating Lists in Python –

In python lists are represented by square brackets ([ ]) and all the individual elements inside a list is separated by commas.

Here is an example of a list in Python.

companies = ['Google','Microsoft','Apple','Facebook','Netflix','Airbnb']

You can also create an empty list like this

In [8]: empty_list = []

In [9]: type(empty_list)
Out[9]: list

You can also have lists inside a list.

lst = [2, 6, 5, [3, 'brad'], 7]

Accessing Elements in a List –

To access the elements in a list, we use the position or index of an item in a list. To access an element in a list, first we write the name of the list followed by the index of an item inside a square bracket.

Let’s say you want to access Apple from the companies list.

In [3]: companies[2]
Out[3]: 'Apple'

Indexing Starts at 0 –

In python and many other programming languages, the index starts at 0 not 1. If you look carefully you can see that to access the 3rd element ‘Apple’ from the companies list, I used companies[2] instead of companies[3]. So to get the first item, you have to write companies[0] and to get second you have to write companies[1] and so on.

In [4]: # get first item from list

In [5]: companies[0]
Out[5]: 'Google'

In [6]: # get second item from list

In [7]: companies[1]
Out[7]: 'Microsoft'

Let’s say you want to get ‘brad’ from the lst. To do that you have to write

In [10]: lst = [2, 6, 5, [3, 'brad'], 7]

In [11]: lst[3][1]
Out[11]: 'brad'

Here, we first tell python to get the 4th element from the list which is itself is a list, next we tell python to get the second element from that list.

Negative Indexing –

You can also do negative indexing with python. To get the last item from a list you write lst[-1] and to get the second last element you write lst[-2].

In [12]: # get the last item using negative indexing

In [13]: lst[-1]
Out[13]: 7

In [14]: # get second last

In [15]: lst[-2]
Out[15]: [3, 'brad']

List Slicing in Python –

You can also get multiple items at a time using list slicing in python. The syntax for list slicing is

list[start:end]

When we do list slicing the start index is inclusive but the end index is exclusive.

In [17]: companies
Out[17]: ['Google', 'Microsoft', 'Apple', 'Facebook', 'Netflix', 'Airbnb']

In [18]: companies[1:5]
Out[18]: ['Microsoft', 'Apple', 'Facebook', 'Netflix']

For example, companies[1:5] returns a list with elements at index 1, 2, 3 and 4, but not 5.

In our upcoming posts, we will talk about adding and removing items from a list and many other kind of operations you can do with lists, so make sure to subscribe to our blog below to get the latest updates.

Leave a Reply