Computer Science, asked by nitingarg9059, 11 months ago

Python List Comprehension?

Answers

Answered by Jyotimodi
0

List Comprehensions in Python

List Comprehensions

List comprehensions provide a concise way to create lists.

It consists of brackets containing an expression followed by a for clause, then

zero or more for or if clauses. The expressions can be anything, meaning you can

put in all kinds of objects in lists.

The result will be a new list resulting from evaluating the expression in the

context of the for and if clauses which follow it.

The list comprehension always returns a result list.

Answered by poojan
1

List Comprehension in Python :

  • List Comprehension is a one statement expression in python that is used to create a list using an already existing list following a compact syntax.

  • They can be used in an effective way, but are not much user friendly to understand. One needs to take minutes with lot of concentration to understand such expressions. So, if you are going to create bit lists, better to ignore this approach.

  • Syntax : [expression for element in iterable if condition]

        It is equivalent to the looping :

        for element in iterable:

           if condition:

                expression

        Where, in list comprehension, the iterable will be a list.

Example :

Printing the cubes of even numbers present in the range of 1 to 10.

Using list comprehension:

cubes = [x**3 for x in range(1,10) if x%2==0]

print(cubes)

or simply,

[x**3 for x in range(1,10) if x%2==0]

Output :

[8, 64, 216, 512]

Explanation :

Here, expression = x**3 which will be executed whenever the element in the list iterable ranging from 1 to 10, excluding 10, [1, 2, 3, 4 , 5, 6, 7, 8, 9] satisfies the condition of getting reminder 0 when divided by 2 as in i%2==0

In normal looping way, it is written as :

for x in range(1,10):

   if x%2==0:

       print(x**3)

or

l=[]

for x in range(1,10):

   if x%2==0:

       l.append(x**3)

print(x)

Learn more :

1. Write a list comprehension that builds a list of the even numbers from 1 to 10 (inclusive).

https://brainly.in/question/16086791

2. What is the difference between a python tuple and python list?

https://brainly.in/question/13319756

Similar questions