Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
8,568 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
8,568 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.