How do you slice a number in a list in python?

On this page: slice indexing with [:], negative indexing, slice and negative indexing on strings.

Video Tutorial

How do you slice a number in a list in python?

Python 3 Changesprint(x,y) instead of print x, y

Video Summary

  • It's possible to "slice" a list in Python. This will return a specific segment of a given list. For example, the command myList[2] will return the 3rd item in your list (remember that Python begins counting with the number 0).
  • You can expand the length and change the location of the list segment returned using a colon in your command. Ex: myList[2:5] will return the 3rd through 5th items in your list. Typing myList[:5] will return every item up to the 5th item on a list, while myList[2:] on the other hand, with a colon following the numeral, will return every item starting with the 3rd.
  • Python can also return a segment of a list counting from the end. This is done simply by inserting a negative before the desired numerals within the slice command. Ex: myList[-5] will return your fifth from last entry.

Learn More

Practice

The list is fox = ['the', 'quick', 'brown', 'fox', 'jumps', 'over']. How do you get ['quick', 'brown', 'fox'] from this list, using slicing? Try in IDLE shell.
Using slicing, how can you get 'dental' from 'incidentally'? How about 'action' from 'traction'? Try in IDLE shell.

Explore

  • On to the next tutorial!


Next: List Operators Up: Lists, Tuples and Dictionaries Previous: List Data   Contents The slicing operations introduced in Section 2.4.3 also work with lists, with one very useful addition. As well as using slicing to extract part of a list (i.e. a slice on the right hand sign of an equal sign), you can set the value of elements in a list by using a slice on the left hand side of an equal sign. In python terminology, this is because lists are mutable objects, while strings are immutable. Simply put, this means that once a string's value is established, it can't be changed without creating a new variable, while a list can be modified (lengthened, shortened, rearranged, etc.) without having to store the results in a new variable, or reassign the value of an expression to the original variable name.

Consider a list with 5 integer elements:

>>> thelist = [0,5,10,15,20]
Now suppose we wish to change the central three elements (5, 10 and 15, at positions 1, 2 and 3 in the list) to the values 6, 7, and 8. As with a string, we could extract the three elements with a statement like:
>>> thelist[1:4]
[5, 10, 15]
But with a list, we can also assign values to that slice:
>>> thelist[1:4] = [6,7,8]
>>> thelist
[0, 6, 7, 8, 20]

If the number of elements in the list on the right hand side of the equal sign is not equal to the number of elements implied by the subscript of the slice, the list will expand or shrink to accomodate the assignment. (Recall that the number of elements in a slice is the higher valued subscript minus the lower valued subscript.) The following examples illustrate this point:

>>> words = ['We','belong','to','the','knights','who','say','"Ni"']
>>> words[1:4] = ['are']
>>> words
['We', 'are', 'knights', 'who', 'say', '"Ni"']     
>>> words[1:2] = ['are','a','band','of']
['We', 'are', 'a', 'band', 'of', 'knights', 'who', 'say', '"Ni"']
Note that when we are replacing a slice with a single element, it must be surrounded by square brackets, effectively making it into a list with one element, to avoid a TypeError exception.

Assignments through slicing differ from those done with simple subscripting in that a slice can change the length of a list, while assignments done through a single subscript will always preserve the length of the list. This is true for slices where both of the subscripts are the same. Notice the difference between the two expressions shown below:

>>> # using a single subscript
>>> x = ['one','two','three','four','five']
>>> x[1] = ['dos','tres','cuatro']
>>> x
['one', ['dos', 'tres', 'cuatro'], 'three', 'four', 'five']       
>>> # using a slice 
>>> x = ['one','two','three','four','five']
>>> x[1:1] = ['dos','tres','cuatro']
>>> x
>>> ['one', 'dos', 'tres', 'cuatro', 'two', 'three', 'four', 'five']
In the final example, we were able to insert three elements into an list without replacing any elements in the list by assigning to a slice where both subscripts were the same.

Another use of slices is to make a separate modifiable copy of a list. (See Section 6.1 to understand why this is important.) In this case, you create a slice without either a starting or ending index. Python will then make a complete copy of the list

>>> x = ['one','two','three']
>>> y = x[:]
>>> y
['one', 'two', 'three']

One final use of slices is to remove elements from an array. If we try to replace a single element or slice of an array with an empty list, that empty list will literally replace the locations to which it's assigned. But if we replace a slice of an array with an empty list, that slice of the array is effectively removed:

>>> a = [1,3,5,7,9]
>>> a[2] = []
>>> a
[1, 3, [], 7, 9]
>>> b = [2,4,6,8]
>>> b[2:3] = []
>>> b
[2, 4, 8]

Another way to remove items from a list is to use the del statement. You provide the del statement with the element or slice of a list which you want removed, and that element or slice is removed without a trace. So to remove the second element from the list a in the previous example, we would use the del statement as follows:

>>> del a[2]
>>> a
[1, 3, 7, 9]
The del statement is just as effective with slices:
>>> nums = ['one','two','three','four','five']
>>> del nums[0:3]
>>> nums
['four', 'five']
In the previous example, the same result could be obtained by assigning an empty list to nums[0:3].

Next: List Operators Up: Lists, Tuples and Dictionaries Previous: List Data   Contents Phil Spector 2003-11-12

How do you slice a number in Python?

Python slice() Function The slice() function returns a slice object. A slice object is used to specify how to slice a sequence. You can specify where to start the slicing, and where to end. You can also specify the step, which allows you to e.g. slice only every other item.

Can we do slicing in list?

As well as using slicing to extract part of a list (i.e. a slice on the right hand sign of an equal sign), you can set the value of elements in a list by using a slice on the left hand side of an equal sign. In python terminology, this is because lists are mutable objects, while strings are immutable.

How does slicing work in Python list?

With this operator, one can specify where to start the slicing, where to end, and specify the step. List slicing returns a new list from the existing list. If Lst is a list, then the above expression returns the portion of the list from index Initial to index End, at a step size IndexJump.

Can we slice integer in Python?

slice() Parameters start (optional) - Starting integer where the slicing of the object starts. Default to None if not provided. stop - Integer until which the slicing takes place. The slicing stops at index stop -1 (last element).