0

I was just trying to write a code in Python for Euler Problem 15 (https://projecteuler.net/problem=15), concerning Lattice Paths.

I wanted to write something which would return (1,2,1), (1, 3, 3, 1), (1, 4, 6, 4, 1) etc. I wrote the following:

lijst = [1,1]
temp = [1,1]
for a in range(2,21):
    temp.append(1)
        for b in range(1,a):
        temp[b] = lijst[b-1] + lijst[b]
    lijst = temp
    print a, lijst

To my surprise, this didn't work. At the start of the second 'for'-loop, somehow the append doesn't only work on 'temp', but also on 'lijst'. I got the code working by changing:

lijst = temp

into:

lijst = [a for a in temp]

What's the problem hear? Am I missing something out on the behaviour of lists?

Thanks!

tmfrk
  • 1
  • 1
    What you're missing isn't the behavior of lists, but the behavior of variables and values in general. When you do `lijst = temp`, that just makes `lijst` into another name for the same value that `temp` is a name for. So, since they're both naming the same value, changing that value under one name is obviously changing the same value under a different name. If you want to make a copy in Python, you have to explicitly make a copy (although you can do it a lot more simply with `temp[:]` or `list(temp)` instead of `[a for a in temp]`). – abarnert May 30 '18 at 21:37
  • Also see [this blog post](https://nedbatchelder.com/text/names.html) by Ned Batchelder. (The presentation linked at the top is probably even better, but I haven't viewed it myself…) – abarnert May 30 '18 at 21:41
  • Thank you for your elaborate response! Will watch the presentation, great link. – tmfrk May 30 '18 at 22:07
  • While you're at it, bookmark [the blog index](https://nedbatchelder.com/blog/tag/python.html) and skim it when you have time later; this definitely isn't the only case where he manages to take something confusing and make it obvious, while our official SO answer is only so-so… – abarnert May 30 '18 at 22:12

0 Answers0