Creating a set filled with letters from the alphabet in python
I am trying to create a set of the letters from the alphabet and I'm not sure why the code is not working. Python gives me an error saying that the "global name 'a' is not defined." Any ideas? Thank you in advance.
s = set()
s = {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}
Solution 1:
a
, b
, ... on their own are not strings, they are names. Python strings must be enclosed in single quotes ('a'
), double quotes ("a"
) or triple quotes ("""a"""
or '''a'''
). So, the correct version of your code would be:
# s = set() - this is useless, the next line is already creating a set
s = {'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'}
Having said that, a much cleaner way of doing this is to use Python's built-in set and string.ascii_lowercase like so:
import string
s = set(string.ascii_lowercase)
Solution 2:
try this
import string
s = set(string.ascii_lowercase)
Solution 3:
@lenik answer is the best, but it's good to remember, that every string is also an iterable sequence and can be passed to set()
. So, instead of list of one-letter literals you can just:
letters = set("abcdefghijklmnopqrstuwxyz")