FAQ: Working with Lists in Python - Slicing Lists II

This community-built FAQ covers the “Slicing Lists II” exercise from the lesson “Working with Lists in Python”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Computer Science
Data Science

FAQs on the exercise Slicing Lists II

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

3 posts were split to a new topic: Difference between slicing lists with positive and negative indexes?

I highly recommend rewording this section, because the current description of “omitting the final index” is confusing and I had to change and run it a few times to understand what it was doing. Or maybe an example with more than just four elements.

Thanks.

1 Like

fruits = [“apple”, “cherry”, “pineapple”, “orange”, “mango”]

If we want to select the first n elements of a list, we could use the following code:

fruits[:n]

For our fruits list, suppose we wanted to slice the first three elements.

The following code would start slicing from index 0 (omitted) and up to index 3 .

print(fruits[:3])

Would output:

[‘apple’, ‘cherry’, ‘pineapple’]

My question is:
Isn’t the last element omitted? So index number 3 is omitted, not 0?
I’m guessing it’s a proofing mistake, right?

Another question

We can do something similar when we want to slice the last n elements in a list:

fruits[-n:]

For our fruits list, suppose we wanted to slice the last two elements.

This code slices from the element at index -2 up to the last index(ommited). I understand correctly that it slices [-2:0], omitting the last index?

print(fruits[-2:])

Would output:

[‘orange’, ‘mango’]

List slicing works by including the element at the start index and excluding the element at the end index. For example, lst[1:5] would include the elements at indexes 1, 2, 3, and 4. The same goes for slices that involve negative indices. lst[-4:-2] would include the elements at indexes -4 and -3.

You can take a look at the documentation for more information.

Side note: you can format code in your posts using the </> button.

Thanks a lot for the responses!
I thought that was the way it works, so the course material should be corrected I think. I have bolded what I think is wrong.
When we write
lst[:3] we list the indexes “0”, “1” and “2”, omitting the last one, while the course material says “0” is omitted, in which case it wouldn’t display the first element of the list and it would display the last.

Nice catch! I’ll submit a bug report, thanks!

Happy to help, and thanks again!

1 Like

I am counfued by colon in this part.

suitcase = ["shirt", "shirt", "pants", "pants", "pajamas", "books"] # Your code below: colon_after = suitcase[2:] print(colon_after) colon_after_negative = suitcase[-2:] print(colon_after_negative) colon_before = suitcase[:2] print(colon_before) colon_before_negative = suitcase[:-2] print(colon_before_negative)

for example in this code:
colon after number 2 ([2:]), the outcome shows, first 2 elements were sliced. but for -2, the outcome shows last 2 elements were kept. I am totally lost. why the colon is placed same, but outcomes are different?

>>> suitcase = ["shirt", "sweater", "pants", "shorts", "pajamas", "books"]
>>> suitcase[2:]
['pants', 'shorts', 'pajamas', 'books']
>>> suitcase[-2:]
['pajamas', 'books']
>>> 
#                   [   2   :    ..        ..        ..   ]
["shirt", "sweater", "pants", "shorts", "pajamas", "books"]
#                                      [   -2     :  ..   ]

I am sorry what’s this?

It shows where index 2 captures the rest of the list (colon after) , and where index -2 captures a slice.

list[start:]   => slice the list from start to last index

When there is no step value, the default is left, from and including start index, to right, with step value 1. When end is omitted, the end is index[len(lst)].

what does list[-start:](negative start) mean? does it mean slice the list from last to start?

A list has two indices per element. The positive indices start at zero and increase to the end of the list, from left to right. The negative indices start at -1 and decrease to the beginning of the list, from right to left.

To find the negative index of any element we just need to subtract the length of the list. Say the length is 6.

+           -
0 - 6  =>  -6
...
5 - 6  =>  -1

To find the positive index we add the length…

 -          +
-6 + 6  =>  0
...
-1 + 6  =>  5

To answer your question, it doesn’t matter which index we use as the start, the direction is from left to right. We’ve only chosen our index from the right .

Plus 2 is negative 4 plus 6.

>>> suitcase[-4:]
['pants', 'shorts', 'pajamas', 'books']
1 Like

fruits[:n] - what does the “n” represent. Is it calling for the first letter “n” in the list?
Is it being used as a variable? I am confused? I understand positive and negative integers and how they are called in regards to the list.

It is a variable used in second position of a slice configuration. [:n] is index 0 up to but not including index n.

1 Like

fruits = [“apple”, “cherry”, “pineapple”, “orange”, “mango”]
print(fruits[:n])

I put this in pythonfiddle to see what output it would return. It didn’t return anything. So just so I am clear n is the representation of a variable that has a default value of 0. Yet it can be replaced with any number value positive or negative in the list. As a stand alone though it’s default value is index 0?

In this representation, [:n] the first position does default to zero when left vacant, as above. n must be defined, but can as you observe be either positive or negative. Since a slice is virtual, any value will be valid, whether it renders anything or not.

1 Like

The first element in the list is always 0. Does this change? I ran across some lessons where it seems like the first element was being represented as “1” and the zero was the entire list. This has me confused because I want to count from left to right zero every time.

I am not referring to negative integers.

The first index of a list is always zero, or the negative of the length.

      0  1  2  3  4  5  6
a = [ _, _, _, _, _, _, _ ]
      ^
  -len(a)               -1