HomePagev2 Forums Python Discussions List Comprehension

  • Sri lakshmi Parvathi Devi

    Member
    September 12, 2020 at 6:22 am

    List Comprehension:

    List:

    A list is a collection which is ordered and changeable.In Python lists are written with square brackets.

    List Comprehension:

    list comprehension is an elegant way to define and create a list in Python.

    It complete substitute for lambda function as well as the functions map(),filter() and reduce().

    By using list comprehension we can reduce our code.

    for example:

    creation of list using for loop:

    A=[]

    for  i  in  ‘learn’:

    A.append(i)

    print(A)

    output:

    [‘l’,’e’,’a’,’r’,’n’]

    creation of list using list comprehension:

    A=[  i    for   i   in   ‘learn’]

    print(A)

    Output:

    [‘l’,’e’,’a’,’r’,’n’]

    Print a list of  Even numbers   in   a  particular  range:

    A=[]

    for  i  in   range(20):

    if   i%2==0:

    A.append(i)

    print(A)

    Print  a list of  Even numbers  in   a  particular  range  by  using  List Comprehension:

    A=[ i  for  i  in  range(20)  if   i%2==0]

    print(A)

    I hope you understood List Comprehension with this examples.

     

Log in to reply.

Original Post
0 of 0 posts June 2018
Now