Home > OS >  .append() is replacing element, instead of adding new element to the list
.append() is replacing element, instead of adding new element to the list

Time:12-07

I am trying to create a cipher program, here text entered by the user will be shifted to the letters according to the shift variable. so here I have created an empty list called encrypt and trying to append characters after shifting them to the list. But it's just replacing the letter in the list instead of adding a new item in the list.

Here's the code:

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

#direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))

#TODO-1: Create a function called 'encrypt' that takes the 'text' and 'shift' as inputs.
def encrypt(text,shift):
    for letter in text:
        encrypted = []
        position = alphabet.index(letter)   shift
        encrypted.append(alphabet[position])
    print(''.join(encrypted))
    
encrypt(text,shift)

Thank you

CodePudding user response:

You are basically overwriting your list everytime in the loop. here

def encrypt(text,shift):
    for letter in text:
        encrypted = [] #This runs every iteration, so there will be only 1 at end
        position = alphabet.index(letter)   shift
        encrypted.append(alphabet[position])
    print(''.join(encrypted))

Move it out of the loop, things must be fine.

def encrypt(text,shift):
    encrypted = []
    for letter in text:

        position = alphabet.index(letter)   shift
        encrypted.append(alphabet[position])
    print(''.join(encrypted))
  • Related