IdeaMonk

thoughts, ideas, code and other things...

Saturday, September 19, 2009

Easy to define lists in Python

Right now I just realized how easy does Python make it to define a list of all alphabets, uppercase and lower case + numbers.
While in C/C++ I would go for an array like this -

char foo[] = { '0', '1', '2', '3', '4', '5' .... 'a', 'b', 'c' .... 'Y', 'Z' };

I hope you can understand how painful would it be two write all elements encapsulated in their respective single quotes... and imagine if after that you need to shuffle them!
However in Python I wouldn't actually need to go through that pain, I can simply write -

foo = [k for k in "0123456789abcdefghijklmnopqrstuv....Z"]

That's is, I got a list of all those characters, easy to understand, easy to type out.
Then as for shuffling it you can go for random

import random
random.shuffle (foo)
# want to get a string out of it? here it is
randomcombination = ''.join(foo)


Oh by the way, a small chit-chat with @l0nwlf actually uncovered that there is the string library... and then there are so many predefined things that we could've actually used -

>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
>>> string.letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
>>> print string.digits + string.letters
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
>>>
listing = [k for k in string.digits+string.letters]

Just some small things that make Python your weapon of choice when you sit down to work upon some idea you got in bathroom.
After looking at some amazing 1liners for euler and hearing about LCs and itertools, I think the following is seriously gonna be true one day... and the pythonists shall inherit the earth...

Labels: ,

4 Comments:

At September 20, 2009 at 4:03 AM , Blogger l0nwlf said...

Love the XKCD, python do make you feel free of gravity as if u'r flying. d00d dun't miss exploring LCs, u'll love every single bit of it :)

PS. the term should be pythonista ;)

 
At September 20, 2009 at 11:17 AM , Blogger Prabhat Godse said...

cartoons are hilarious :)

 
At October 4, 2009 at 6:33 PM , Blogger sykora said...

You do realize that ``[k for k in string]`` can still be shortened to ``list(string)`` right? :)

 
At October 4, 2009 at 6:43 PM , Blogger IdeaMonk said...

Yes, after "Intro to Python" it became clear immediately, I try using list(...) whenever possible now :)

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home