Cara menggunakan python list set slice


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:

Table of Contents

  • Introduction to Python List slice notation
  • Python List slice examples
  • 1) Basic Python list slice example
  • 2) Using Python List slice to get the n-first elements from a list
  • 3) Using Python List slice to get the n-last elements from a list
  • 4) Using Python List slice to get every nth element from a list
  • 5) Using Python List slice to reverse a list
  • 6) Using Python List slice to substitute part of a list
  • 7) Using Python List slice to partially replace and resize a list
  • 8) Using Python list slice to delete elements
  • How do you cut a list in Python?
  • Can lists be sliced?
  • How do I slice a data list in Python?
  • How do you cut a list in half in Python?

>>> 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

Summary: in this tutorial, you’ll learn about Python list slice and how to use it to manipulate lists effectively.

Introduction to Python List slice notation

Lists support the slice notation that allows you to get a sublist from a list:

sub_list = list[begin: end: step]

Code language: Python (python)

In this syntax, the begin, end, and step arguments must be valid indexes. And they’re all optional.

The begin index defaults to zero. The end index defaults to the length of the list. And the step index defaults to 1.

The slice will start from the begin up to the end in the step of step.

The begin, end, and step can be positive or negative. Positive values slice the list from the first element to the last element while negative values slice the list from the last element to the first element.

In addition to extracting a sublist, you can use the list slice to change the list such as updating, resizing, and deleting a part of the list.

Python List slice examples

Let’s take some examples of using the list slice.

1) Basic Python list slice example

Suppose that you have the following list of strings:

colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']

Code language: Python (python)

The following example uses the list slice to get a sublist from the colors list:

colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'] sub_colors = colors[1:4] print(sub_colors)

Code language: Python (python)

Output:

['orange', 'yellow', 'green']

Code language: Python (python)

The begin index is 1, so the slice starts from the 'orange' color. The end index is 4, therefore, the last element of the slice is 'green'.

As a result, the slice creates a new list with three colors: ['orange', 'yellow', 'green'].

This example doesn’t use the step, so the slice gets all values within the range without skipping any elements.

2) Using Python List slice to get the n-first elements from a list

To get the n-first elements from a list, you omit the first argument:

list[:n]

Code language: Python (python)

The following example returns a list that includes the first three elements from the colors list:

colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'] sub_colors = colors[:3] print(sub_colors)

Code language: Python (python)

Output:

['red', 'orange', 'yellow']

Code language: Python (python)

Notice that the colors[:3] is equivalent to the color[0:3].

3) Using Python List slice to get the n-last elements from a list

To get the n-last elements of a list, you use the negative indexes.

For example, the following returns a list that includes the last 3 elements of the colors list:

colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'] sub_colors = colors[-3:] print(sub_colors)

Code language: Python (python)

Output:

['blue', 'indigo', 'violet']

Code language: Python (python)

4) Using Python List slice to get every nth element from a list

The following example uses the step to return a sublist that includes every 2nd element of the colors list:

colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'] sub_colors = colors[::2] print(sub_colors)

Code language: Python (python)

Output:

['red', 'yellow', 'blue', 'violet']

Code language: Python (python)

5) Using Python List slice to reverse a list

When you use a negative step, the slice includes the list of elements starting from the last element to the first element. In other words, it reverses the list. See the following example:

colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'] reversed_colors = colors[::-1] print(reversed_colors)

Code language: Python (python)

Output:

['violet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red']

Code language: Python (python)

6) Using Python List slice to substitute part of a list

Besides extracting a part of a list, the list slice allows you to change the list element.

The following example changes the first two elements in the colors list to the new values:

colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'] colors[0:2] = ['black', 'white'] print(colors)

Code language: Python (python)

Output:

['black', 'white', 'yellow', 'green', 'blue', 'indigo', 'violet']

Code language: Python (python)

7) Using Python List slice to partially replace and resize a list

The following example uses the list slice to replace the first and second elements with the new ones and also add a new element to the list:

colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'] print(f"The list has {len(colors)} elements") colors[0:2] = ['black', 'white', 'gray'] print(colors) print(f"The list now has {len(colors)} elements")

Code language: Python (python)

Output:

The list has 7 elements ['black', 'white', 'gray', 'yellow', 'green', 'blue', 'indigo', 'violet'] The list now has 8 elements

Code language: Python (python)

8) Using Python list slice to delete elements

The following shows how to use the list slice to delete the 3rd, 4th, and 5th elements from the colors list:

colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'] del colors[2:5] print(colors)

Code language: Python (python)

Output:

['red', 'orange', 'indigo', 'violet']

Code language: Python (python)

Summary

  • Use a list slice to extract a sublist from a list and modify the list.

Did you find this tutorial helpful ?

How do you cut a list in Python?

How to slice a list, string, tuple in Python.

Basic usage of slices. [start:stop] [start:stop:step].

Extract from the end with a negative value. Negative values for start and stop. ... .

Slice object by slice().

Assigning values by slices..

Slices for a list of lists..

Slices make shallow copy..

Slices for strings and tuples..

Can lists be sliced?

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 do I slice a data list in Python?

The format for list slicing is [start:stop:step]. start is the index of the list where slicing starts. stop is the index of the list where slicing ends. step allows you to select nth item within the range start to stop.

How do you cut a list in half in Python?

This can be done using the following steps:.

Get the length of a list using len() function..

If the length of the parts is not given, then divide the length of list by 2 using floor operator to get the middle index of the list..

Slice the list into two halves using [:middle_index] and [middle_index:].

Apa itu slicing di Python?

Slicing merupakan teknik memilih data dari sebuah set data. Misal kita memiliki data berat badan mahasiswa: 65, 78, 77, 100, 56. Maka jika kita urutkan maka urutan pertama adalah 65, urutan kedua adalah 78, urutan ketiga adalah 77, urutan keempat adalah 100, dan urutan terakhir adala 56.

Apa itu set pada Python?

Apa Itu Tipe Data Set Python Tipe data set merupakan tipe data yang digunakan untuk menyimpan banyak nilai dalam satu variabel dan yang tidak beraturan serta memiliki nilai yang unik (tidak ada duplikasi).

Apa itu built in pada Python?

Didalam bahasa pemrograman Python terdapat dua jenis yaitu Built-In Function dan User Defined Function. Built-In Function adalah sebutan untuk fungsi yang sudah ada secara bawaan dari dalam bahasa pemrograman. Sedangkan User Defined Function adalah fungsi yang kita (sebagai programmer) membuatnya sendiri.

Apa itu Len di Python?

2. Len() Kita masuk dalam pembahasan yang pertama yaitu fungsi Len(). Fungsi len() digunakan untuk mengidentifikasi dan mengetahui seberapa panjang jumlah item atau anggota pada suatu objek. Penerapan fungsi len() ini bisa dipraktekkan pada berbagai jenis data seperti data sequence dan data collection.