1

So I've seen a code that goes like

name = "Python"

class Language:
    name = "Java"
    list1 = [name] * 3  
    list2 = [name for i in range(3)]

print(Language.list1)
print(Language.list2)

And the output is

['Java', 'Java', 'Java']
['Python', 'Python', 'Python']

Why is the output not "Java" both times?

  • Hah, that's a fun edge case you've got there. I'm sure there's a rational explanation, but wheeew! – kindall Jan 09 '23 at 13:21
  • i guess you wouldn't be able to explain it ryt – Prison Mike Jan 09 '23 at 13:24
  • 1
    The duplicate question linked has a decent explanation. I learned something! – kindall Jan 09 '23 at 13:38
  • am kinda new to python... i kinda need explanation in my own question please. if its possible – Prison Mike Jan 09 '23 at 16:06
  • 1
    Basically, the scope of a class definition does not behave like other scopes, and is skipped when a list comprehension or function needs to access a nonlocal variables. – kindall Jan 09 '23 at 16:54
  • 1
    If the class namespace wasn't skipped, you'd be able to access class variables in your methods, too, even though that scope didn't exist anymore. – kindall Jan 09 '23 at 16:56

0 Answers0