1
486views
What is list comprehension? explain with example.
1 Answer
2
5views

Solution

List Comprehension

  • list comprehension offer a way to create lists based on existing iterable. When using list comprehension, lists can be built by using ant iterable , including strings, list, tuple.

ex: (using for loop)

input :

       mystr = 'ques'
       mylist = [ ]
       for c in my str:
           mylist.append(c)
       print(mylist)

output : ['q', 'u', 'e', 's']

  • the same output can be achived using list Comprehension with just one line of code.

Syntax :


[ expression for item in iterable ]

OR

[ expression for item in iterable if condition ]


Example (using List Comprehension):

                 mylist = [c for c in 'ques']
                 print(mylist)

output : ['q', 'u', 'e', 's']

  • Similarly, we can use list comprehensions in many cases where we want to create a list out of other iterable, let’s see another example of the use of List Comprehension.

Example (Using for loop):

               mylist = [ ]
               for i in range(1,6):
                   mylist.append(i**2)
               print(mylist)

output : [1, 4, 9, 25]

Example (using List Comprehension):

                 mylist = [i**2 for i in rang(1,6) ]
                 print(mylist)

output : [1, 4, 9, 25]

Please log in to add an answer.