Eric Yamga
Eric Yamga

Reputation: 111

Nested list loop indexing

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

Upvotes: 0

Views: 33

Answers (1)

yatu
yatu

Reputation: 88236

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']]

Upvotes: 3

Related Questions