Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python semi-noob, can someone explain why this phonomena occurs in 'Lists'

Tags:

python

I'm working on a small app that pulls data out of a list stored in a list, passes it through a class init, and then displays/allows user to work. Everything was going fine until i tried to format the original 'list' in the IDLE so it was easier to read (for me). so I'd change 9 to 09, 8 to 08. etc It was a simple formating/spacing change and it broke the entire god damn program, citing 'invalid token'. WTF is this, I thought. So then I opened the interpreter and started typing:

>x = [5,5]  #Control

>x

[5, 5]

>>> y=[05,05]    #control2

>>> y

[5, 5]

>>> z = [05, "ge"]  #test. 'Integer', before string, apparantly works.


>>> z

[5, 'ge']

> a = ["ge", 09]  #test2. String, before 'integer', cocks things up.

SyntaxError: invalid token

>>> b= ["ge", 9]    #test3, this works fine.


>>> b


['ge', 9]

I guess my question is... why does this occur? Why is python interpret these integers as 'tokens' when they follow strings, but as integers when they follow integers?

like image 896
Matt McCarthy Avatar asked Dec 05 '22 06:12

Matt McCarthy


1 Answers

It's nothing to do with lists or strings. When you prefix a number with 0, it's interpreted as octal. And 9 is not a valid octal digit!

Python 2.7.6 
Type "help", "copyright", "credits" or "license" for more information.
>>> 09
  File "<stdin>", line 1
    09
     ^
SyntaxError: invalid token
>>> 011
9

Note that in Python3, this gives you the error for any 0-prefixed number, presumably to reduce confusion of the type you are experiencing. To specify octal in Python3, you must use 0o as a prefix.

Python 3.3.3 
Type "help", "copyright", "credits" or "license" for more information.
>>> 09
  File "<stdin>", line 1
    09
     ^
SyntaxError: invalid token
>>> 011
  File "<stdin>", line 1
    011
      ^
SyntaxError: invalid token
>>> 0o11
9
>>> 0o9
  File "<stdin>", line 1
    0o9
     ^
SyntaxError: invalid token
>>>
like image 196
Blorgbeard Avatar answered Dec 08 '22 05:12

Blorgbeard