tags:

views:

142

answers:

7
+1  Q: 

Python NameError

list1 = [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z]

for item in list1:
    print item

Not sure why the above code is throwing this error:

NameError: "name 'a' is not defined"
+6  A: 

You have to put strings into (double) quotes

list1 = ["a","b","c",...] 

should work

Mef
Aaah! :P Thanks
Nimbuz
Yeah, I guess we all know beeing a blockhead... sometimes it's just too obvious :D
Mef
whether it's double or single quotes is irrelevant.
SilentGhost
k, adjusted it ;-)
Mef
or a I sometimes like to "a b c d e".split() but for this case Roger Pate's answer is more apt.
James Brooks
+1  A: 

String literal should be enclosed in quotes :)

list1 = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
Satoru.Logic
+8  A: 

In addition to using quotes properly, don't retype the alphabet.

>>> import string
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> L = list(string.ascii_lowercase)
>>> print L
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', ...
>>> help(string)
Roger Pate
Well, a string is iterable, so one can do: for s in string.ascii_lowercase: print(s)
Hamish Grubijan
Thanks for the tip! :)
Nimbuz
+1  A: 

Picking and choosing the best of the previous posts this is how I would do it since a string can be iterated.

>>> import string
>>> for letter in string.ascii_lowercase:
...     print(letter)
... 
lewisblackfan
+1  A: 

python interprets the members in your list as variables,you shoud enclose them in

' or "

appusajeev
A: 

When I need to make a list of characters, if they aren't already available in something defined in the std lib, and if I really need a list and not just a string, I use this form:

punc = list(r";:`~!@#$%^&*()_-+=[]{}\|,./<?>")
vowels = list("aeiou")  # or sometimes list("aeiouy")

Much simpler than all those extra quotes and commas, and it's clear to the reader that I really meant I wanted a list, and not just a string.

Paul McGuire
+1  A: 

Every language needs to differentiate between constants and names/variables. The most confusing is when you have to differentiate between string constants and identifiers/names/variables.

A shell (sh, bash, ksh, csh, cmd.com etc) tends to use constants; so you can just type a constant and you prefix a name/variable with a special character ($ for unix shells, % for cmd.com etc) when you want its value.

$ echo hello
hello
$ echo $PWD
/home/tzot
$ cd /tmp
$ cd $OLDPWD

Most other generic programming languages tend to use variables much more than constants, so it's the other way around: you just type the name of a variable and you (typically) enclose string constants in quotes ('', "", [] etc):

# assumed: a_name= "the object it points to"

>>> print ("a constant")
a constant
>>> print (a_name)
the object it points to
ΤΖΩΤΖΙΟΥ