Hello Steven, Thanks a lot for the detailed answer. I will implement your suggestions. Really appreciate it.
Thanks and Regards, Sumod On Fri, Jan 27, 2012 at 4:34 AM, Steven D'Aprano <st...@pearwood.info>wrote: > spa...@gmail.com wrote: > >> Hello, >> >> My code is - >> >> l = len(m) >> item = str(m[1]) >> for i in range(2,l): >> item = item + "-" + str(m[i]) >> >> This code is part of a bigger function. It works fine. But I am not happy >> with the way I have written it. I think there is a better (Pythonic) way >> to >> rewrite it. >> If anyone knows how to improve this snippet, I would be very thankful. >> > > (1) Never use "l" as a variable name, as it looks too much like 1. > > > (2) Use meaningful names. When posting snippets for help, you should show > example data. > > > (3) You almost never need to iterate over an index by hand. Instead > iterate over the items themselves. That is, instead of this: > > for i in len(sequence): > do_something_with( sequence[i] ) > > do this instead: > > for item in sequence: > do_something_with( item ) > > > and similar variations. > > > (4) When you want only part of a sequence, use slicing to extract just the > parts you care about. > > > (5) When assembling strings from substrings, never use repeated > concatenation using + as that can be EXTREMELY slow. Use str.join to build > the string in one assignment, instead of multiple assignments. > > Your code shown above is *very* inefficient and will be PAINFULLY slow if > m is very large. To understand why, you should read this article: > > http://www.joelonsoftware.com/**articles/fog0000000319.html<http://www.joelonsoftware.com/articles/fog0000000319.html> > > In this case, you can replace your snippet with this: > > result = '-'.join(str(item) for item in m[1:]) > > > > For example: > > py> m = [1, 2, "hello world", (23, 42), 5] > py> '-'.join(str(item) for item in m[1:]) > '2-hello world-(23, 42)-5' > > > > -- > Steven > > ______________________________**_________________ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor> > -- http://spawgi.wordpress.com We can do it and do it better.
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor