Osama Akhtar
Osama Akhtar

Reputation: 123

Using a function on each element of a list

I have a list (decrypted_list) which contains four integer elements I have to decrypt. The function's job is to decrypt the code, and it's logic is correct. After defining the function, I want to call it on every element of decrypted_list to decrypt its elements.

encrypted_list = [7, 1, 0, 2]

def decrypter(number):
    for number in encrypted_list:
        if (number + 4) < 10:
            return (number + 4)
        elif (number + 4) > 10:
            return (number + 4) % 10

decrypted_list = [decrypter(x) for x in encrypted_list]

However, the output is not what I expect:

Expected: [1, 5, 4, 6]
Actual: [1, 1, 1, 1]

Please help! I am new to Python. :)

Upvotes: 2

Views: 92

Answers (3)

gstukelj
gstukelj

Reputation: 2551

Others already pointed out the problem in your code. I'd like to point out a redundancy in your function. This would produce the same output: decrypted_list = [(x + 4) % 10 for x in encrypted_list]. Or if you want to have in a function:

def decrypter(number):
    return (number + 4) % 10

decrypted_list = [decrypter(x) for x in encrypted_list]

Since x % 10 == x if x < 10.

Upvotes: 2

Sweeper
Sweeper

Reputation: 274835

Your function should look like this:

def decrypter(number):
    if (number + 4) < 10:
        return (number + 4)
    elif (number + 4) > 10:
        return (number + 4) % 10

You shouldn't use a for loop here because you are going to use this function on each element of the list in the last line of your code:

decrypted_list = [decrypter(x) for x in encrypted_list]

As you have said, that function only decrypts one number, so it doesn't need to know about the whole list. encrypted_list should not appear in that function.

Adding that for loop in will cause the function's behaviour to change - whatever number you pass in, it will only decrypt the number 1, because that is the first item of the list. The for loop doesn't actually loop through the list, because it hits return on the first iteration.

Upvotes: 2

Pierre V.
Pierre V.

Reputation: 1625

There is no point in looping over encrypted_list in your decrypter function. This function should just look at the number argument - it does not need to know about the encrypted_list variable.

The loop operation itself should only take place in your list comprehension ([decrypter(x) for x in encrypted_list]).

Change your function to the following and you should be fine:

def decrypter(number):
  if (number + 4) < 10:
      return (number + 4)
  elif (number + 4) > 10:
      return (number + 4) % 10

Upvotes: 3

Related Questions