1

I'm fairly new to python and I'm currently working on a program that will encrypt and decrypt strings. As part of it, I need the individual letters of the string to each be added to an empty list; for example, the string 'hello' would be entered into a list list like so:

['h','e','l','l','o']

The part of the code that is giving me this error can be found below. Thanks.

emptyList=[]
message=input("What Would You Like To Encrypt?\n")

messageLength=len(message)
for count in range(0,messageLength):
        emptyList=[]
        emptyList[count].append(message[count])
1
  • 3
    emptyList[0] does not exist when emptyList is []. You might want to empyList.append(message[count]). That said, it'd likely be easier to do emptyList = list(message) Commented Mar 7, 2016 at 16:51

2 Answers 2

4

You are trying to address indices in an empty list:

>>> lst = []
>>> lst[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> lst[0] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range

If you wanted to add elements to a list, just use list.append() directly on the list object itself to create more indices; don't create new empty lists each time:

emptyList=[]
messageLength=len(message)
for count in range(0,messageLength):
    emptyList.append(message[count])

Not that you need to be this elaborate, the following is enough:

emptyList = list(message)

list() takes any iterable and adds all the elements of that iterable to a list. Since a string is iterable, producing all the characters in that string, calling list() on a string creates a list of those characters:

>>> list('hello')
['h', 'e', 'l', 'l', 'o']
Sign up to request clarification or add additional context in comments.

Comments

2

Basically you want just read from the input and then output a list

Python 2.7

message=raw_input("What Would You Like To Encrypt?\n")
print list(message)

Python 3.X

message=input("What Would You Like To Encrypt?\n")
print(list(message))

Output

If you input Hello

['H', 'e', 'l', 'l', 'o']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.