2.3. Part of a list

A specific group of items in a list is called a slice.

Slicing a List

For example you want the first 3 elements of a list:

Notice that foods[0:3] return the foods with index 0, 1 and 2. As with the range(), Python don't include food with index 3.

If you want the 3rd, 4th, and 5th items in a list, you can start with index 2 and end with index 5.

If you omit the first index in a slice, it will automatically start at the beginning of the list:

Similarly, you can omit the second index if you want the rest of the list to be included:

You can also use negative index. Say we want to make a list of your 3 last orders:

Looping in a Slice

In the last example, say we want to print our last 3 orders using for loop. We can use the slice in for loop as well as follows:

Copying a List

To copy a list, you can use a slice of the original list with both indexes omitted (like this foods[:]). This is basically a copy of the original list.

Say your friend order some additional foods and you also decided to order extra food. Here, you order an ice cream while your friend order a fried chicken.

This way you can make a copy of whatever list you want. However, if you don't put [:] when you assign a copy, the variable my_orders and friend_orders will be the same, resulting undesired orders at the end. Try it out!

Exercise 2.3

  1. Slices
    From the list of stationary do the following:

    • Use a slice to print the first three items from that list as follows:
      The first three items in the list are:
      pen
      pencil eraser
      Hint: Use end=" "

    • Use a slice to print the third to sixth items from that list as follows:
      The third to sixth items in the list are:
      eraser ruler highlighter calculator

    • Use a slice to print the last four items in the list as follows:
      The last four items in the list are:
      sharpener compass cutter marker

  2. My Stationary, Your Stationary
    Using the previous stationary list, make a new copy of that list, call it friends_stationary.

    • Delete the last item in my_stationary list using del then add "stapler" to the beginning of the list using insert().

    • Delete the first item in friends_stationary list then add "correction tape" to the list using append().

    • Prove that you have two separate lists. Print the message
      My items are:
      and then use a
      for loop to print the first list.

    • Print the message
      My friend's items are:
      and then use a for loop to print the second list. Make sure each new items is stored in the appropriate list.