-2

I wrote a function that is supposed to insert a 2D list into a table.

This is the code:

seats_plan = [[True, True, True, True, True], [True, True, True, True, True], [True, True, True, True, True], [True, True, True, True, True], [True, True, True, True, True]]
def print_database(seats_plan):
    for row in seats_plan:
        row.insert(0, seats_plan.index(row))
    seats_plan.insert(0, [' ', '0', '1', '2', '3', '4'])
    for k in seats_plan:
        for char in k:
           if char is True:
               print '.',
           elif char is False:
               print 'x',
           else:
               print char,
        print

and the output is:

  0 1 2 3 4
0 . . . . .
1 . . . . .
2 . . . . .
3 . . . . .
4 . . . . .

but it also changed seats_plan, so if I call the function again it inserts the numbers again. How can I make it insert it only once without changing the original seats_plan?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

2 Answers2

1

Don't change the list, because it is only a reference, e.g. the same as the original list. Print the numbers, when needed:

seats_plan = [[True, True, True, True, True], [True, True, True, True, True], [True, True, True, True, True], [True, True, True, True, True], [True, True, True, True, True]]
def print_database(seats_plan):
    print ' ', '0', '1', '2', '3', '4'
    for row, seats in enumerate(seats_plan):
        print row,
        for seat in seats:
            print '.' if seat else 'x',
        print

or with list comprehension

def print_database(seats_plan):
    plan = [ '%d %s' % (row, ' '.join('.' if seat else 'x' for seat in seats))
        for row, seats in enumerate(seats_plan)]
    plan.insert(0, '  ' + ' '.join(str(c) for c in range(len(seats))))
    print '\n'.join(plan)
Daniel
  • 42,087
  • 4
  • 55
  • 81
0

The problem is that you an expectation that Python is passing by value, but Python always references. Consider this SO post: Emulating pass-by-value...

You can create a copy in your first couple lines with:

from copy import deepcopy
def print_database(seats_plan):
    seats_plan_copy = deepcopy(seats_plan)
Community
  • 1
  • 1
M. K. Hunter
  • 1,778
  • 3
  • 21
  • 27