Python Lists

Python Lists are the most flexible and ordered collection object. Lists can contain any type of data types: numbers, strings, and even lists. The best way to understand list in python is to understand by using it. A list can be easily created with [ ]. Now let’s do some operation to understand the List in python.

Basic Python Lists Operations

Lists are sequences in Python, we use it to store data of any data type. It is very easy and flexible to use. Now let’s start with the very basic functions of lists.

Also, Read – Physical Computing with Python.

To check the length of a list:

len([1, 2, 3]) #Length


To Concatenate two lists:

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

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

To repeat the items inside a list:

['Ni!'] * 4 # repeat

[‘Ni!’, ‘Ni!’, ‘Ni!’, ‘Ni!’]

Python Lists Iteration and Comprehensions

Now let’s see how we can loop over a list in python, first let’s use the membership method, which ensures whether the item is present inside the sequence or not:

3 in [1, 2, 3] # Membership


Now let’s iterate over a list, which is very simple:

for x in [1, 2, 3]: print(x, end=' ')

Or you can use it like this:

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


List comprehensions are a way to build a new list by applying an expression to each item in a sequence (really, in any iterable), and are close relatives to for loops:

res = [c * 4 for c in 'SPAM'] res

[‘SSSS’, ‘PPPP’, ‘AAAA’, ‘MMMM’]

The above comprehension repeats each alphabet of the string four times. Lists Comprehensions are a shorter way for performing loops, now let’s see how we could do the above comprehension using a for loop:

res = [] for c in 'SPAM': res.append(c * 4) res

[‘SSSS’, ‘PPPP’, ‘AAAA’, ‘MMMM’]

Matrixes using Python Lists

A list in python is an array in other programming languages. A matrix is a multidimensional array, which means it is a list of nested sublists. Now let’s start with a 3×3 two-dimensional array:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] matrix[1]

[4, 5, 6]

matrix[1] gave us [4, 5, 6] instead of [1, 2, 3] because indexing starts from 0 in programming.



matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] matrix[1][0]


I hope you liked this article on Lists in Python. Feel free to ask your valuable questions in the comments section below.

Also, Read – How to Choose an Algorithm in Machine Learning?

Follow Us:

Leave a Reply