Hello I am learning python and I am confused with the count for my python for loop.
I am implementing the function make_str_from_column: This creates a string from a list of lists, representing a column.
What I dont understand is that when I set the count to 0 I get an error message. It works when I set the count to -1? would be grateful for your feedback, many thanks.
Here is the error message
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
make_str_from_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 1)
File "/Users/<name>/Downloads/a3.py", line 77, in make_str_from_column
new_element = board[count][column_index]
IndexError: list index out of range
>>>
Here is the function
def make_str_from_column(board, column_index):
""" (list of list of str, int) -> str
Return the characters from the column of the board with index column_index
as a single string.
>>> make_str_from_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 1)
'NS'
>>> make_str_from_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 2)
'TO'
>>> make_str_from_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 3)
'TB'
>>> make_str_from_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 0)
'AX'
>>> make_str_from_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B'], ['X', 'S', 'O', 'B']], 1)
'NSS'
"""
# intialise a count for the loop
count = -1
# create an empty list to save the indexed elemenets into
new_list = []
for i in board:
count = count + 1
new_element = board[count][column_index]
new_list.append(new_element)
string_new_list = ''.join(new_list)
return string_new_list
Also is there a more pythonic way of writing this