15

This is the function for printing all values in a nested list (taken from Head first with Python).

def printall(the_list, level):
    for x in the_list:
        if isinstance(x, list):
            printall(x, level=level + 1)
        else:
            for tab_stop in range(level):
                print("\t", end='')
        print(x)

The function is working properly.

The function basically prints the values in a list and if there is a nested list then it print it by a tab space.

Just for a better understanding, what does end=' ' do?

I am using Python 3.3.5

For 2.7

f =  fi.input( files = 'test2.py', inplace = True, backup = '.bak')
for line in f:
    if fi.lineno() == 4:
        print line + '\n'
        print 'extra line'
    else:
        print line + '\n'

as of 2.6 fileinput does not support with. This code appends 3 more lines and prints the appended text on the 3rd new line. and then appends a further 16 empty lines.

martineau
  • 99,260
  • 22
  • 139
  • 249
Rajath
  • 1,258
  • 2
  • 10
  • 18

2 Answers2

35

The default value of end is \n meaning that after the print statement it will print a new line. So simply stated end is what you want to be printed after the print statement has been executed

Eg: - print ("hello",end=" +") will print hello +

Bhargav Rao
  • 41,091
  • 27
  • 112
  • 129
  • 7
    My aspergers requires me to correct the output to `hello + `. – smassey Dec 05 '14 at 09:13
  • 1
    @smassey Yeah, but the problem is even though I have given a space, it is not shown :( – Bhargav Rao Dec 05 '14 at 09:15
  • 3
    You can't really just end and end doesn't really equate to a newline `end=' '` actually means that you want a space after the end of the statement instead of a new line character. So you can continue on the same line with "Whatever" Example `print ("Hello World") x = '20' print (x, x, x, x) print ("HI HI")` Would print out 1st line = "Hello World" 2nd line = 20 20 20 20 3rd line = "HI HI" However Example `print ("Hello World") x = '20' print (x, x, x, x, end=' ') print ("HI HI")` Would print out 1st line = Hello World 2nd line = 20 20 20 20 HI HI – imbatman Sep 25 '16 at 22:18
  • end will work on python 3 not 2.7 – Shyam Gupta Jun 16 '18 at 11:40
  • @ShyamGupta yes – Bhargav Rao Jun 16 '18 at 11:42
4

See the documentation for the print function: print()

The content of end is printed after the thing you want to print. By default it contains a newline ("\n") but it can be changed to something else, like an empty string.

BOTJr.
  • 1,321
  • 5
  • 26
  • 52
RemcoGerlich
  • 27,022
  • 4
  • 55
  • 74