How To Use List Comprehension Without [ ] in Python

In this post, we will learn how to use list Comprehension without [ ] in Python as we can use the generator expression and we have used the same to show the example.

Comprehension

List Comprehension

A Python list comprehension list of squares brackets containing the expression, or the elements is executed for each element along with the for loop to iterate over each element in the python list. By default we use the square brackets ‘[ ]’ but here we are going to do the same thing using a generator expression where we do not need to use the ‘[ ]’ square brackets.

It is somewhat similar to that of list comprehensive but it has a difference in its return, It returns a generator object rather than a list. But the list is similar to that as the list is comprehensive but the only difference here is it uses ‘( )’ in place of ‘[ ]’. And for the same, we have given an example below and understand the concept for implementation in our project.

# Original list
my_list = [1, 2, 3, 4, 5]

# Generator expression is not used square brackets
new_list = (x * 2 for x in my_list)

# Iterate over the generator object and print the values
for value in new_list:
    print( value)

Here in the above example, we have used the expression¬† ‘(x*2 for x in my list)’ for creating a generator object which iterates each and every element of ‘my list’ and at the same time multiple the value of x which we got by 2. And here we are iterating all the elements of the list in fact generator list we are using and printing all the elements as per our requirements.

There is a drawback regarding the generator list that is we can only iterate the list only once and we can not go through the list again for going to the list again we need to use the list() function and for the same, we have given an example below which we can implement in our project and get it done.

# Original list
my_list = [1, 2, 3, 4, 5]

# Generator expression where square brackets are not used
new_list = (x * 2 for x in my_list)

# Convert the generator object to a list
new_list = list(new_list)

# Print the new list
print( new_list)

As the code given above is self explained where how we can use it.

 

 

To learn more about How To Use List Comprehension Without [ ] in Python visit:  by geeks for Geeks

To learn more about solutions to different problems and tutorials for the concepts we need to know to work on programming along with different ways to solve any generally asked problems: How To Pass-Variables From A Java & Python Client To A Linux/Ubuntu Server Which Is Running C?.

Leave a Comment

%d bloggers like this: