-1

I have the following code:

def encrypt(plaintext, k):
    return "".join([alphabet[(alphabet.index(i)+k)] for i in plaintext.lower()])

I don't understand how python can read this kind of syntax, can someone break down what's the order of executions here?

I came across this kind of "one-line" writing style in python a lot, which always seemed to be so elegant and efficient but I never understood the logic.

Thanks in advance, have a wonderful day.

  • It creates a list then converts that to a string. Look up "list comprehension". – 001 Jul 10 '20 at 12:33

1 Answers1

0

In Python we call this a list comprehension. There other stackoverflow posts that have covered this topic extensively such as: What does “list comprehension” mean? How does it work and how can I use it? and Explanation of how nested list comprehension works?.

In your example the code is not complete so it is hard to figure what "alphabet" or "plaintext" are. However, let's try to break down what it does on the high level.

"".join([alphabet[(alphabet.index(i)+k)] for i in plaintext.lower()])

Can be broken down as:

"".join(  # The join method will stitch all the elements from the container (list) together
    [
        alphabet[alphabet.index(i) + k]  # alphabet seems to be a list, that we index increasingly by k
        for i in plaintext.lower()
        # we loop through each element in plaintext.lower() (notice the i is used in the alphabet[alphabet.index(i) + k])
    ]
)

Note that we can re-write the for-comprehension as a for-loop. I have created a similar example that I hope can clarify things better:

alphabet = ['a', 'b', 'c']
some_list = []

for i in "ABC".lower():
    some_list.append(alphabet[alphabet.index(i)])  # 1 as a dummy variable

bringing_alphabet_back = "".join(some_list)
print(bringing_alphabet_back) # abc

And last, the return just returns the result. It is similar to returning the entire result of bringing_alphabet_back.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
alt-f4
  • 2,112
  • 17
  • 49