Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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
14,241 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
14,241 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.