eozzy
eozzy

Reputation: 68710

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"

Upvotes: 1

Views: 3953

Answers (7)

tzot
tzot

Reputation: 95991

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

Upvotes: 1

PaulMcG
PaulMcG

Reputation: 63749

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.

Upvotes: 0

appusajeev
appusajeev

Reputation: 2299

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

' or "

Upvotes: 1

snarkyname77
snarkyname77

Reputation: 1174

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)
... 

Upvotes: 1

Leo
Leo

Reputation: 38190

You have to put strings into (double) quotes

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

should work

Upvotes: 7

Roger Pate
Roger Pate

Reputation:

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)

Upvotes: 12

satoru
satoru

Reputation: 33225

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"]

Upvotes: 2

Related Questions