---
# System prepended metadata

title: Slicing in Python
tags: [IB, Computer Science, python]

---

# B2.1 2 bis Slicing in Python

:::info

This is a note part of the coding course for IB Computer Science program. If you want to check out other parts of the same course you can see them in [This link of teaching material](/68GDv_RgT-yh9oERMvdnFw)

:::

:::warning
:warning: :test_tube:  Note still under testing :test_tube: :warning: 
:::



This note is related to [B2.2.1 and B2.2.2 Lists in Python](/RWrVgWBOTOebitrb0MSFVw) and to [String exercises in python](/y_afcRmLQcysv05xlSqRuQ) and explains slicing. 

![image](https://hackmd.io/_uploads/SkU50wzrZl.png)
_Bread, sliced [source](https://www.pexels.com/photo/sliced-bread-on-white-cloth-11842169/)_

When we have a list (or a string) we might want to have just a part of that list, for that we're going to use slicing. 

This is very common in programming and yes is something that you need to be used to if you want to program in python and IB as far as I can tell expects you to know this (or the java version if you do java).

Slicing is similar in syntax to access (we use brackets `[]`) but we need one or two colons (`:`) inside of it. 

So `cream[a]` is accessing one element of cream but `montecarlo[4:b]` is a slice of montecarlo. 

The syntax is as follows:

`elementWeWantToSlice[start:end:step]`


* **start**     Optional. Starting index of the slice. Defaults to 0.
* **stop**    Optional. The last index of the slice or the number of items to get. **NOT INCLUDED**. Defaults to len(elementWeWantToSlice).
* **step**   Optional. Extended slice syntax. Step value of the slice. Defaults to 1. 

:::info
**Default** as a verb in this case means that if you don't specify it in the code which value is going to take. It's the *default* value.
:::

## Cool things to remember

### Negative indexes 

You can use the negative indexes. So if you want all but the last element you can write

`myList[:-1]`

### Reversing a list

`myList[::-1]`

In other programming languages this is a mess to write already. 

### Adding together 

If you have a number a that is between 0 and len(myList) it happens that `myList[:a]` and `myList[a:]` include between them all the elements withaut repetition. Is the perfect slice.

For example 

```python!
quote = "Be gentle to other people"
a = 5
print(quote[:a]) #Be ge
print(quote[a:]) #ntle to other people
```


## Exercises with lists

Let's supose that in a list we have the names of some students and after them their grades. 

For this you can create in the interpreter this list:

```python!
exerciseList = ["Pepa", 5, 
                "Pipo", 4, 
                "Pepe", 6,  
                "Thomas Jefferson" , 3]
#Thomas Jefferson needs to put more effort on it. You can do it Tommy!
```

and then print the slice. So, for example if we want the whole list

```python=
print(exerciseList)
```

If we want to reverse it to get 

`[3, 'Thomas Jefferson', 6, 'Pepe', 4, 'Pipo', 5, 'Pepa']`

we need to write

```python=
print(exerciseList[::-1])
```

Because it's how we reverse lists (or strings)

### Only until Thomas Jefferson (not included)

Write the statement to get the sublist of all the students and grades except from Thomas Jefferson 

### Only Thomas Jefferson 

Write the statement to get the sublist of the name of the last student and his grade.

### Only Pepa and her grade

Write the statement to get the sublist of the name of the Pepa and her grade.

### Pipo and Pepe, better together 

Write the statement to get the sublist of the name of Pipo and Pepe and their grades

Next exercise include also using step

### Only the names 

We want only the names in the same order.

### Pepe and Pipo, together better

Write the statement to get the sublist of the name of Pipo and Pepe and their grades but in reverse order. 

### Only the grades 

We want only the names in the same order. Write the statement to get it from the list.

### Only the two last grades 

Now we want only the 2 last grades. Write the statement to get it from the list.

## Exercises with strings

We can do the same thing with a string, so let's work on it and you will find that is pretty much the same as with list if you think that any character is an element of the sequence. 

Let's use this string:

```python!
leCorbusierQuote = "I prefer drawing to talking. Drawing is faster, and leaves less room for lies."
```
_(Le Corbusier was a very important architect of the 20th Century)_

If we want to have only to "I prefer" we can write 

`print(leCorbusierQuote[:8])`

Now, you can find the result and then you write the input needed using a slice.

* drawing to talking
* Drawing is faster, and leaves less room for lies.
* I prefer drawing to talking.
* lies
* lies. (with the period)

Now messing around with the step

* .seil rof moor ssel sevael dna ,retsaf si gniwarD .gniklat ot gniward referp I
* Iredwgoai.ri  sra ase of e
* rfrdai

### Extra ball

You can use also find to find an index of a specific substring to know where you need to go. For example, to get the second sentence you can use `print(leCorbusierQuote[leCorbusierQuote.find(".")+2:])`. The +2 is because you need, not the dot but the starting letter 2 characters after. 

More on that on [String exercises in python](/y_afcRmLQcysv05xlSqRuQ)


### Exercise from exam 

This can be solved in other ways using `split()` but also can be solved using slicing, find and rfind. 

Write the output of this solution proposed by one student of this [exercise](https://hackmd.io/-ylq-DUoTKOS6qGCiq3JRA?both#Exam-exercise-reading-data-from-a-csv-fil):

```python!
sampleLine = "072,Botswana,PAISES,23.8028,-22.1802"

sampleList = [
        sampleLine[sampleLine.find(",")+1:sampleLine.find(",PAISES")],
        sampleLine[sampleLine.find(",PAISES,")+8:sampleLine.rfind(",")],
        sampleLine[sampleLine.rfind(","):]
    ]
print(sampleList)

```

Solution:

:::spoiler
![image](https://hackmd.io/_uploads/SJpybcPUWg.png)

:::

## Exam like exercise

:::warning
:warning: I haven't seen any pure slicing exercises in IB exams and I think they would be unlikely to happen. But I did some exams specifically to practice this.
:::

1)	Write the output of this program in Python: 

![image](https://hackmd.io/_uploads/H1uKL-9U-e.png)

Solution
:::spoiler
![image](https://hackmd.io/_uploads/Syyu0dJv-g.png)

:::

2) Write the code needed to output the following in Python using slicing given this string:

![image](https://hackmd.io/_uploads/B1SBA_1wbg.png)

![image](https://hackmd.io/_uploads/r1sdAOyDWg.png)

Solution:

:::spoiler
(for the first there is other solution)
![image](https://hackmd.io/_uploads/BJlqR_1vbg.png)
:::


## Reference 

https://www.luisllamas.es/en/python-slices/

https://python-reference.readthedocs.io/en/latest/docs/brackets/slicing.html