alter / modify a list as well as iterate on its items / objects
John Hunter
jdhunter at ace.bsd.uchicago.edu
Tue May 25 17:30:29 EDT 2004
>>>>> "Derek" == Derek Basch <dbasch at yahoo.com> writes:
Derek> Hello, Can anyone point me towards an article or explain
Derek> how to properly alter a list as well as iterate on its
Derek> items? For example:
Derek> input:
Derek> word = ["albert", "likes", "surfing!"]
Derek> for word in sentence: word += "foo"
Derek> result:
Derek> word = ["albertfoo", "likesfoo", "surfingfoo"]
Realize that you cannot alter strings because strings are not
mutable. You can, however, create a list of new strings on the fly
using list comprehensions.
sentence = ["albert", "likes", "surfing!"]
sentence = [ word+'foo' for word in sentence]
And if the list contains mutable items, you can mutate them in place.
Eg, a list of lists
seqseq = [ [1,2,3], [4,5,6], [7,8,9] ]
for seq in seqseq:
seq.append(1)
print seqseq
Hope this helps,
JDH
Derek> __________________________________ Do you Yahoo!? Friends.
Derek> Fun. Try the all-new Yahoo! Messenger.
Derek> http://messenger.yahoo.com/
Derek> -- http://mail.python.org/mailman/listinfo/python-list
More information about the Python-list
mailing list