On 5/7/2016 10:14 PM, Stephen Hansen wrote:
On Sat, May 7, 2016, at 06:16 PM, DFS wrote:

Why is it better to zip() them up and use:

for item1, item2, item3 in zip(list1, list2, list3):
      do something with the items

than

for j in range(len(list1)):
    do something with list1[j], list2[j], list3[j], etc.

Although Chris has a perfectly good and valid answer why conceptually
the zip is better, let me put forth: the zip is simply clearer, more
readable and more maintainable.
>
This is a question of style and to a certain degree aesthetics, so is
somewhat subjective, but range(len(list1)) and list1[j] are all
indirection, when item1 is clearly (if given a better name then 'item1')
something distinct you're working on.


The lists I actually use are:

for j in range(len(nms)):
     cSQL = "INSERT INTO ADDRESSES VALUES (?,?,?,?,?)"
     vals = nms[j],street[j],city[j],state[j],zipcd[j]


The enumerated version would be:

ziplists = zip(nms,street,city,state,zipcd)
for nm,street,city,state,zipcd in ziplists:
     cSQL = "INSERT INTO ADDRESSES VALUES (?,?,?,?,?)"
     vals = nm,street,city,state,zipcd


I guess the enumeration() is a little nicer to look at. Why do you think it's more maintainable?


Aside: I haven't tried, but is 'names' a bad idea or illegal for the name of a python list or variable?


Thanks

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to