0

I am trying to create a list of characters based on a list of words i.e.

["BOARD", "GAME"] -> [["B","O"...], ["G","A","M"...]

From my understanding, I have an IndexError because my initial boardlist does not contain a predetermined the amount of lists.

Is there a way for to create a new list in boardlist according to number of objects in board?

I don't know if I'm being clear.

Thank you.

board=["BOARD", "GAME"]
boardlist=[[]]
i=0
for word in board:
    for char in word:
        boardlist[i].append(char)
    i=i+1
print(boardlist)

IndexError: list index out of range

1
  • 1
    Your boardlist is a list with a single list inside. However, when you iterate over your board list, you will come to a point where i=1. As boardlist has no second element, you get the "list out range" error. Commented Jul 10, 2019 at 15:31

1 Answer 1

3

Note that this can be done in a much simpler way by taking a list of each string in the board, as the list constructor will be converting the input iterable, in this case a string, to a list of substrings from it:

l = ["BOARD", "GAME"] 

[list(i) for i in l]
# [['B', 'O', 'A', 'R', 'D'], ['G', 'A', 'M', 'E']]

Let's also find a fix to your current approach. Firstly boardlist=[[]] is not a valid way of initializing a list (check what it returns). You might want to check this post. Also instead of incrementing a counter you have enumerate for that:

boardlist = [[] for _ in range(len(board))]
for i, word in enumerate(board):
    for char in word:
        boardlist[i].extend(char)

print(boardlist)
# [['B', 'O', 'A', 'R', 'D'], ['G', 'A', 'M', 'E']]
Sign up to request clarification or add additional context in comments.

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.