I made a little "console" that splits the command with split()
. I am separating the "command" (the first "word" from the input()
) from the "arguments" coming after the first word. Here's the code that generates an error:
cmdCompl = input(prompt).strip().split()
cmdRaw = cmdCompl[0]
args = addArgsToList(cmdCompl)
addArgsToList()
function:
def addArgsToList(lst=[]):
newList = []
for i in range(len(lst)):
newList.append(lst[i+1])
return newList
I try to add every word after cmdRaw
to a list called args
which is returned by addArgsToList()
. But what I get instead is:
Welcome to the test console!
Type help or ? for a list of commands
testconsole >>> help
Traceback (most recent call last):
File "testconsole.py", line 25, in <module>
args = addArgsToList(cmdCompl)
File "testconsole.py", line 15, in addArgsToList
newList.append(lst[i+1])
IndexError: list index out of range
I cannot figure out why I get an IndexError
because as far as I know, newList
can be dynamically allocated.
Any help?
You should do like this:
if you wish to avoid first element to be appended
def addArgsToList(lst=[]):
newList = []
for i in range(1,len(lst)):
newList.append(lst[i])
return newList
if you just trying to copy the elements in a new list just do this:
newList = lst[1:].copy()