Thursday, 22 June 2017

python - Is there a way to rewrite a list comprehension as a for loop?

You mean to extract a boring old regular for loop from a list-comprehension?


list1=[string1[i:i+int1] for i in range(0, len(string1), int1)]

Becomes:


list1 = list()
for i in range(0, len(string1), int1):
list1.append(string1[i:i+int1])

This would be useful if you wanted to add exception handling, logging, or more complex functions or behaviors while you iterate over your data.


For instance:


list1 = list()
for i in range(0, len(string1), int1):
log.info('in loop: i={}'.format(i))
try:
data = string1[i:i+int1]
except:
log.error('oh no!')
# maybe do something complex here to get some data anyway?
data = complex_function(i)
log.debug('appending to list: data={}'.format(data))
list1.append(data)

But generally speaking the list-comprehension is a totally legitimate way to write that.

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...