August 07, 2021    /    Viewed: 242    /    Comments: 0    /    Edit

Examples of how to slice a list in python:

### Create a list in python

Lets first create a list in python

````mylist = ['a','b','c','d','e','f','g','h','i']`
```

To get an element stored in a list using its indexe:

````mylist[0]`
```

returns

````'a'`
```

and

````mylist[4]`
```

returns

````'e'`
```

### Get number of elements in a list

To get the size of a list in python, a solution is to use the built-in function len()

````s = len(mylist)`

`print(s)`
```

returns here

````9`
```

### Get first n elements of a list in python

To get first n elements of a list in python a solution is to do mylist[-n:]. Example, extract only the first 3 elements:

````mylist[:3]`
```

returns

````['a', 'b', 'c']`
```

same as

````mylist[0:3]`
```

also returns

````['a', 'b', 'c']`
```

### Get last n elements of a list in python

To get last n elements of a list in python a solution is to do mylist[-n:]. Example, extract only the last 2 elements:

````mylist[-2:]`
```

returns

````['h', 'i']`
```

Note: same as doing:

````mylist[s-2:s]`
```

also returns

````['h', 'i']`
```

### Get elements between indexes m,n

To get elements between indexes m,n, a solution is to do mylist[m:n]. Example:

````mylist[2:5]`
```

returns

````['c', 'd', 'e']`
```

### Get every nth element in a list

To get for example every 2 element in a list

````mylist[::2]`
```

returns

````['a', 'c', 'e', 'g', 'i']`
```

Another example

````mylist[::3]`
```

returns

````['a', 'd', 'g']`
```

### Get every nth element in a list, between indexes m1,m2

To get every nth element in list, between indexes m1,m2, a solution is to do mylist[m1:m2:n]. Example:

````mylist[0:4:2]`
```

returns

````['a', 'c']`
```

### References

##### Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!