0

I am trying to build a 2-dimensial array which will be used to write values to a CSV file. At the point I am at, the array looks like

[['Filename', 'Date', 'Message']]

Those are the header rows. I need to be able to make a new 2D array which will have my new values placed in the correct indexes. For example,

    my_list_of_csv_readings[index_row][0] = "file1.txt"
    my_list_of_csv_readings[index_row][1] = "04/27/2021"
    my_list_of_csv_readings[index_row][2] = "Hello World"

As you can see, I am just trying to add the values to the 2D array but assigning them to the indexes. The desired 2D array after inserting values would be:

[["Filename", "Date", "Message"], ["file1.txt", "04/27/2021", "New Message"]]

How can I ignore the fact that the index is out range and create a new list with the desired output?

mastercool
  • 463
  • 12
  • 35
  • https://stackoverflow.com/questions/10712002/create-an-empty-list-in-python-with-certain-size Does this solve your question? – 101donutman Apr 27 '21 at 20:46

3 Answers3

3

You can't ignore it. If you need to add rows, you need to use append or extend. If you need random access, then you need a dict, not a list.

    my_list_of_csv_readings.append( ["file1.txt","04/27/2021"."Hello World"] )

Or, if you insist:

    my_list_of_csv_readings.append( [] )
    my_list_of_csv_readings[-1].append("file1.txt")
    my_list_of_csv_readings[-1].append("04/27/2021")
    my_list_of_csv_readings[-1].append("Hello World")
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
0

This might not be your prefered solution but it works:

lst = [['value', 'value', 'value']]

lst.append(['value'])
lst[1].append('other value')
lst[1].append('third value')
print(lst)

# prints: [['value', 'value', 'value'], ['value', 'other value', 'third value']]
Have a nice day
  • 1,007
  • 5
  • 11
0

You could just use the append method to add the values:

a = [['Filename', 'Date', 'Message']]
a.append(["file1.txt", "04/27/2021", "New Message"])
print(a)

Output: [['Filename', 'Date', 'Message'], ['file1.txt', '04/27/2021', 'New Message']]

Ishwar
  • 338
  • 2
  • 11