Hi, I struggle to understand the slicing code here “decade = decade[:-1]” :
for age in final_ages:
if age == "Unknown":
decade = age
else :
decade = str(age)
decade = decade[:-1]
decade = decade + "0s"
decades.append(decade)
Initially I wrote: " decade = decade[1:]"
I see the difference when looking at the final “decades” list, but I am missing why.
Pretty sure it has been seen in a previous lesson, so if you happen to know which one tell me I will retake it as I dont understand my mistake.
Thank you for your help 
Hi Nicolas, welcome to the community!
I think this little summary of this type of list slicing will help:
-
a_list[:x]
when we want to select the first x
elements.
-
a_list[-x:]
when we want to select the last x
elements.
-
a_list[x:]
when we want to select all the elements after the first x
elements
-
a_list[:-x]
when we want to select all the elements up to the last x
elements
In the case of decades, we want to keep all but the last digit and change it so that 34 becomes 30s, 103 becomes 100s, and so on.
With decade[1:]
, this means we’re keeping all but the first element. So then 34
would become 40s
instead of 30s
.
With decade[:-1]
, we’re keeping all but the last element, so 34
becomes 30s
I hope that helps clear things up.
1 Like
Hello april,
Thank you very much for the summary and explanation !
It does indeed clarify everything. 