List comprehension and appending None values

Hey there,

So this is my favorite mistake, unfortunately not mine this time, but whenever I’m conducting code review I’ll always make sure to look for it ( yeah, I’m in QC and I’m evil)

Here’s a simple example of what can go wrong:

 

myList = []

for i in range(3):
internalList = []
for j in range(3):
internalList.append(j)
myList.append(internalList)

print(myList)

So we somehow mustered up the courage to go for list comprehensions ( again, we’re headbanging and can’t really decide why we do what we do! )


>>myList1 = []
>>myList = []
>>myList1.append([myList.append([j for j in range(3)]) for i in range(3)]) >>print(myList1)
[[None, None, None]]
>>print(myList)
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]

Should’ve stopped with myList, eh?
So the last append is trying to append something thinking it’s a list or has a return value where’s there’s nothing. I’ve seen the same mistake in other scenarios as well, e.g. when doing regression testing the inputs cause the function to enter into branches which do not have a return value where’s they should.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s