Skip to content
Advertisement

Error when retrieving nested list values in python

I have this as my code right now
main.py:

help = ["/help", ["This returns a list of all commands"]]
color = ["/color", ["This changes the color of the console"]]
cmds = [help, color]

def getHelp(cmd:str=None):
  if not cmd:
    for index, c in enumerate(cmds):
      for i, help in enumerate(c):
        print(help+":", c[1])
    return 
  print("Retrieving command")
  for c in cmds:
    for help in c:
      if c == cmd[1]:
        print(console_color+help)
      else:
        continue

It returns the first list, but not the second one. Traceback:

Traceback (most recent call last):
  File "main.py", line 93, in <module>
    login()
  File "main.py", line 63, in login
    main()
  File "main.py", line 51, in main
    getHelp()
  File "main.py", line 34, in getHelp
    print(help+":", c[1])
TypeError: can only concatenate list (not "str") to list

How do I fix this?

Advertisement

Answer

Found a fix:

def getHelp(cmd:str=None):
  ct = 0
  if not cmd:
    for c in cmds:
      for help in c:
        ct += 1
        if ct % 2 == 0: # prevents printing the command and desc twice
          continue
        elif ct == len(cmds):
          return
        print(str(help)+":", str(c[1]).strip('[']')) # removes the brackets and quotes

If the count is a multiple of 2, it is skipped (to prevent printing twice). If the count is equal to the amount of commands, the iteration is stopped.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement