Error with for loop

Screen Link: Learn data science with Python and R projects

My Code:

index = 0
for row in data:
    data[index] = row[:-1]
    index =+ 1


What I expected to happen:
[[‘August 19, 1971’, ‘Santa Martha Acatitla’, ‘Mexico’, ‘Yes’], [‘September 25, 2020’, ‘Forest prison, Brussels’, ‘Belgium’, ‘No’, ‘Kristel A.’], [‘May 24, 1978’, ‘United States Penitentiary, Marion’, ‘United States’, ‘No’, ‘Garrett Brock TrapnellMartin Joseph McNallyJames Kenneth Johnson’]]

What actually happened:

[['August 19, 1971', 'Santa Martha Acatitla', 'Mexico', 'Yes'], ['September 25, 2020', 'Forest prison, Brussels', 'Belgium', 'No', 'Kristel A.'], ['May 24, 1978', 'United States Penitentiary, Marion', 'United States', 'No', 'Garrett Brock TrapnellMartin Joseph McNallyJames Kenneth Johnson', "43-year-old Barbara Ann Oswald hijacked a Saint Louis-based charter helicopter and forced the pilot to land in the yard at USP Marion. While landing the aircraft, the pilot, Allen Barklage, who was a Vietnam War veteran, struggled with Oswald and managed to wrestle the gun away from her. Barklage then shot and killed Oswald, thwarting the escape.[10] A few months later Oswald's daughter hijacked TWA Flight 541 in an effort to free Trapnell."]]

Other details:

The first two elements are correct i.e. the details column has been removed. However, in the third row, the details column remains. I am confused if the code worked for the first two iterations, why didn’t it work for the 3rd time?

This is the source of the problem and can be easy to miss.

a += 1 is the same as a = a + 1. However, a =+ 1 is the same as a = (+1).

You are setting the index to 1 for every iteration.

Your first two elements in the output are not correct either, as a result. You get -

instead of

['August 19, 1971', 'Santa Martha Acatitla', 'Mexico', 'Yes', 'Joel David Kaplan Carlos Antonio Contreras Castro']


instead of

['October 31, 1973', 'Mountjoy Jail', 'Ireland', 'Yes', "JB O'Hagan Seamus TwomeyKevin Mallon"]

Once you fix your index update step and re-run the entire code, you should see the correct output.


Thank you so much for the detailed reply! That was very helpful.