Python Python Sequences Sequence Operations Creating Slices

Can I please get help in finding the problem with my code?

Can I please get help in finding the problem with my code?

slices.py
student_gpas = [4.0, 2.3, 3.5, 3.7, 3.9, 2.8, 1.5, 4.0]
sliced_gpas=(3.7, 3.9)

2 Answers

boi
boi
7,587 Points

The challenge wants you to do 2 things, first, it wants you to create a variable called sliced_gpas secondly it wants you to assign this variable to some elements of the student_gpas more specifically it wants you to assign sliced_gpas to a list, which is a collection of 3rd, 4th and 5th elements of the student_gpas list.

Since the challenge requires you to make use of slices, the code you used is completely incorrect πŸ‘‡

student_gpas = [4.0, 2.3, 3.5, 3.7, 3.9, 2.8, 1.5, 4.0]
sliced_gpas=(3.7, 3.9) # No use of slices + wrong values + use of tuple
#Total wrong

πŸ‘‰πŸ‘‰πŸ‘‰SPOILER SOLUTION TO THE CHALLENGE DON'T SEE UNLESS NECESSARYπŸ‘ˆπŸ‘ˆπŸ‘ˆπŸ‘‡πŸ‘‡πŸ‘‡

sliced_gpas = student_gpas[2:5]  # Remember, indices always start at 0, also in slices the stop value is exclusive.

Hi there, thanks for post, i understand why the start was 2 since it was the (3rd place), but I was counting to the fifth place in the data or 6th place instead of 5th because of the zero, why is the 5th place stay the same if we start counting by 0? I appreciate the help.

boi
boi
7,587 Points

If I understand your question correctly, you mean why is the 5th place not included in the list?

That is because, in slices, the stop value is exclusive, take a look at this example πŸ‘‡

a_list = [0, 1, 2, 3, 4 ,5, 6, 7, 8, 9, 10]

Say you want to print the first five values from a_list using slices

print(a_list[0:5]) #or print(a_list[:5])

#output
>>>[0, 1, 2, 3, 4] 

The stop value [start:stop] will not be added into the list because stop values in slices are EXCLUSIVE not inclusive.