Printing Lists in Python (4 Different Ways)

Printing for loop : go from 0 to len (list) and print all list items one at a time using a for loop, this is standard practice.

# Python list printing program
# used for loop

a = [ 1 , 2 , 3 , 4 , 5 ]

  
# print the list using a loop

for x in range ( len (a)):

  print a [x],

Output:

 1 2 3 4 5 
  • Without using loops : * character is used to print list items on one line with a space. To print all elements on new lines or separated by spaces, use sep = ”/ n” or sep = ”,” respectively.

    # Python program for printing a list
    # without using a loop

     

    a = [ 1 , 2 , 3 , 4 , 5 ]

     
    # print the list using the * delimited operator
    # by space

    print ( * a)

     
    # print the list using * and sep statement

    print ( "printing lists separated by commas " )

      

    print ( * a, sep = ","

     
    # print on a new line

    print ( "printing lists in new line" )

      

    print ( * a, sep = "" )

    Output:

     1 2 3 4 5 printing lists separated by commas 1, 2, 3, 4, 5 printing lists in new line 1 2 3 4 5 
  • Convert the list to a string for display : if it is a list of strings, we can simply concatenate them using the function join () , but if the list contains integers, convert it to a string and then use the join () function to join them to the string and print line.

    # Python programs and to print the list
    # by converting the list to
    # string to display

    a = [ " Geeks " , " for " , "Geeks" ]

     
    # print the list using the join () function

    print ( ` ` . join (a))

     
    # print the list by converting the list
    # integers to a string

    a = [ 1 , 2 , 3 , 4 , 5 ]

     

    print str (a) [ 1 : - 1

    Output:

     Geeks for Geeks 1, 2, 3, 4, 5 
  • Map Usage: use map () to convert each item in the list to a string if the list is not a string, then concatenate them:

    # Python list printing program
    # print the list by converting the list
    # integers to string using the map

      

    a = [ 1 , 2 , 3 , 4 , 5 ]

    print ( `` . join ( map ( str , a))) 

      

    print "in new line"

    print ( `` . join ( map ( str , a )))

    Output:

     1 2 3 4 5 in new line 1 2 3 4 5