Search code examples
pythondata-analysis

What is different between `row[3:]` and `row[3]` when I handle csv data file?


import csv
f = open('age.csv',encoding='utf8')
data = csv.reader(f)

for row in data :
    if '신도림' in row[0]:
        for i in row[3:]:
            print(i)

Hello, I just started python data analysis yesterday. csv file that I am using is about population survey based on ages and I got this question now. When I use row[3] it gives me something like this

3
2
6

but when I use row[3:] it gives me the correct answer.

326
457
345
.
.
.

What is different between these two? Thank you for your helping.


Solution

  • The difference is this:

    row[3] is exactly one item (in this case, row): the fourth item (since counting starts at zero).

    row[3:] is a range of many items: from the fourth item in the list to the end of the sequence.

    The [<start-index>:<stop-index>:<step>] syntax is shorthand for creating a slice object. This slice object is a sort of generalized way to index many items in a sequence.