Best Laptop
Python List Comprehension

Python List Comprehension

Hi Friends, welcome to yet another interesting session on Python List Comprehension. Today we will see another way to fill a list with its elements. In previous sessions, we have seen that we can add elements in a list using ‘append’ and ‘insert’ method. However, these methods may not be the best option when you want to add large number of elements in the list since we have add elements one by one.

In such cases, there is another way of creating a list on the go. We don’t need to declare the list in advance. We can create the list and add elements into it at the same time.

Syntax for Python List Comprehension:

1. Generate a list having element value ‘x’ added 8 times:

number = [‘x’ for a in range(8)]
  • We are creating a list named ‘number’
  • ‘x’ denotes the value getting assigned to each subsequent element
  • The ‘for’ loop determines how many elements will be added in the list

2. Generate elements starting from 0 till 7

list = [a for a in range(8)]

Since we are adding element having value ‘a’ and in the for loop we are using ‘a’ as the iterator element.

3. Here a list will be created having numbers starting from 0 and multiplied by 3.

list = [a*3 for a in range(5)]

4. in this case, a list will be created having squares of first 8 integers starting from 0.

sqr = [i ** 2 for i in range(8)]

5. a list will be created here having powers of 2 for first 5 numbers starting from 0.

power = [2 ** i for i in range(5)]

6. Here we are using an existing list ‘power’ in the statement. So, we will see a list having all elements of list ‘power’ multiplied by 2.

list = [2 * i for i in power]

7. Generating a two-dimensional list in above way

2_dim=[[i for i in range(3)] for j in range(4)]

In above example we see two ‘for’ loops. The inner one((first one) with variable ‘i’ generates a list having elements [0,1,2]. The outer loop with variable j repeated this step 4 times. So, we will get a list having 4 elements and each element is a list itself of 3 elements [0,1,2]

8. Accessing elements of a two-dimensional array – to access elements, we must use two values for indexes:

list = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]] – imagine this list.
Now to access element with value 7, we have to use below:
list[2][1] – the first index represents the list element. Second index represents element within the list

To access element with value 3, we have to use below:
list[1][0]

Try more examples on such two-dimensional lists

Previous session on Python Lists: METHODS IN PYTHON LISTS

Leave a Reply

Your email address will not be published. Required fields are marked *

Python 3.11.1 Features