Search code examples
pythonlistsliceelement

Do Elements not start from 0?


I'm a noob, learning via Datacamp (which is really annoying and nitpicky... I could've sworn elements started from 0, counting the first element in the list as 0???? This is the problem.

"Create downstairs again, as the first 6 elements of areas. This time, simplify the slicing by omitting the begin index. Create upstairs again, as the last 4 elements of areas. This time, simplify the slicing by omitting the end index.

I answered with

# Create the areas list
areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50]

# Alternative slicing to create downstairs
downstairs = areas[:-4]

# Alternative slicing to create upstairs
upstairs = areas[5:]

*edited to include areas as I did answer with "areas"

Obviously this is wrong... but I could've sworn I just went through previous questions correctly..... starting with 0... as a rep of the first element... is this different when slicing? Thank you, if you have any resources for better study I would like to understand the syntax of this language better to become more intuitive with it.


Solution

  • The Python slice function does start with 0 as the default starting index, however the end is EXCLUSIVE, meaning it does not include the element at the end of the slice.

    slice([start], stop[, step])
    
    list[:2]    # Elements 0 and 1, stopping at 2, or the first two elements
    list[2:]    # Everything except the first two elements