[Tutor] Still the Python Challenge

Steven D'Aprano steve at pearwood.info
Tue Jan 3 22:20:29 CET 2012


Joaquim Santos wrote:
> Hi list!
> 
> After this past week of no PC and no work, I'm again at the Python
> Challenge Cypher problem.
> I decided to go with the flow and solve it with maketrans (6 lines of
> code against the 40 and going I had already...) and it solved it
> quickly and clean!
> 
> However, and please be sure I don't want to re-invent any wheel, I
> still got some doubts unexplained...
> 
>  - How to correctly populate a list using, for instance, a for loop;


In general:

mylist = []
for value in some_sequence:
     mylist.append( process(value) )


Here's a concrete example: take a list of words, convert to lower case, and 
make them plural:

words = ['CAT', 'DOG', 'TREE', 'CAR', 'PENCIL']
plurals = []
for word in words:
     word = word.lower()
     plurals.append(word + 's')

print(plurals)



>  - how to correctly use join to read the said list in a human friendly way...


I don't understand this question. You can't use join to read a list. Perhaps 
you mean to use join to print a list? Specifically, you use join to build a 
single string from a list of sub-strings.

Given plurals above, we can build a single list of words separated by double 
spaces and a hyphen:

print('  -  '.join(plurals))


To join a list of single characters into a string, use join on the empty 
string. Compare:

chars = ['a', 'b', 'c', 'd']
print(' '.join(chars))
print(''.join(chars))




-- 
Steven


More information about the Tutor mailing list