Search code examples
pythonlistlist-comprehensioncoding-efficiency

List comprehension with if else conditions - Python


so I've been trying to figure out how do I convert the main for loop in this code to a list comprehension for efficiency, I've seen some examples, but none of them seem to cater to this sort of scenario. Any help is appreciated!

key = 'abcdefghij'

def getChunks(key):
    ''' Dividing the key into byte sized chunks'''
    currVal = ''
    remainder = ''
    chunks = []
    currVal = ''


    for char in key:
        if len(currVal) == 8:
            chunks.append(currVal)
            currVal = hex(ord(char))[2:]
        else:
            currVal += hex(ord(char))[2:]

    if len(currVal) == 8:
        chunks.append(currVal)
    elif currVal:
        remainder = currVal

    return (chunks, remainder)


print(getChunks(key))

The desired output dividing the input string/key into byte sized chunks of hexadecimal values + any remainder in the following format

>> (['61626364', '65666768'], '696a')

Oh and this too:

for i in range(1, self.hashCount+1): 
    h = hash(item, i) % self.bitArraySize # Generate Hash

    # set the bit True in bit_array 
    self.bitArray[h] = True

for i in range(1, self.hashCount+1): 
            h = hash(item, i) % self.bitArraySize 
            if self.bitArray[h] == False:
                return False

Solution

  • None of these should be list comprehensions. List comprehensions should not have side-effects (they're a functional programming construct and violating functional programming expectations leads to unmaintainable/unreadable code). In all cases, your loops aren't just building a new list element by element in order, they're also making stateful changes and/or building the list out of order.

    Side-note: if self.bitArray[h] == False: is a slower, unPythonic way to spell if not self.bitArray[h]:; comparing to True and False is almost always the wrong way to go, per the PEP8 style guide:

    Don't compare boolean values to True or False using ==:

     # Correct:
     if greeting:
    
     # Wrong:
     if greeting == True: