Cara menggunakan python slice indices

By On Sunday, October 2nd, 2022 Categories : Tanya Jawab

Cara menggunakan python slice indices – Hi om dan tante semua, Makasih banyak dah mau berkunjung ke situs TrendWisata ini. Pagi ini, kami di situs TrendWisata ingin menampilkan Q dan A yang mantab yang membahas Cara menggunakan python slice indices. Kami persilakan ibu dan bapak menonton berikut ini:

The slice() function returns a slice object that is used to slice any sequence (string, tuple, list, range, or bytes).

Example

text="Python Programing"

# get slice object to slice Python sliced_text = slice(6)

print(text[sliced_text]) # Output: Python

slice() Syntax

The syntax of slice() is:

slice(start, stop, step)

slice() Parameters

slice() can take three 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).
  • step (optional) – Integer value which determines the increment between each index for slicing. Defaults to None if not provided.

slice() Return Value

slice() returns a slice object.

Note: We can use slice with any object which supports sequence protocol (implements __getitem__() and __len()__ method).


Example 1: Create a slice
object for slicing

# contains indices (0, 1, 2)
result1 = slice(3)
print(result1)

# contains indices (1, 3)

result2 = slice(1, 5, 2)

print(slice(1, 5, 2))

Output

slice(None, 3, None)
slice(1, 5, 2)

Here, result1 and result2 are slice objects.

Now we know about slice objects, let’s see how we can get substring, sub-list, sub-tuple, etc. from slice objects.


Example 2: Get substring using slice object

# Program to get a substring from the given string 

py_string = 'Python'

# stop = 3
# contains 0, 1 and 2 indices

slice_object = slice(3)

print(py_string[slice_object]) # Pyt # start = 1, stop = 6, step = 2 # contains 1, 3 and 5 indices slice_object = slice(1, 6, 2) print(py_string[slice_object]) # yhn

Output

Pyt
yhn

Example 3: Get substring using negative index

py_string = 'Python'

# start = -1, stop = -4, step = -1
# contains indices -1, -2 and -3

slice_object = slice(-1, -4, -1)

print(py_string[slice_object]) # noh

Output

noh

Example 4: Get sublist and sub-tuple

py_list = ['P', 'y', 't', 'h', 'o', 'n']
py_tuple = ('P', 'y', 't', 'h', 'o', 'n')

# contains indices 0, 1 and 2

slice_object = slice(3)

print(py_list[slice_object]) # ['P', 'y', 't'] # contains indices 1 and 3

slice_object = slice(1, 5, 2)

print(py_tuple[slice_object]) # ('y', 'h')

Output

['P', 'y', 't']
('y', 'h')

Example 5: Get sublist and sub-tuple using negative index

py_list = ['P', 'y', 't', 'h', 'o', 'n']
py_tuple = ('P', 'y', 't', 'h', 'o', 'n')

# contains indices -1, -2 and -3

slice_object = slice(-1, -4, -1)

print(py_list[slice_object]) # ['n', 'o', 'h'] # contains indices -1 and -3

slice_object = slice(-1, -5, -2)

print(py_tuple[slice_object]) # ('n', 'h')

Output

['n', 'o', 'h']
('n', 'h')

Example 6: Using Indexing Syntax for Slicing

The slice object can be substituted with the indexing syntax in Python.

You can alternately use the following syntax for slicing:

obj[start:stop:step]

For example,

py_string = 'Python'

# contains indices 0, 1 and 2

print(py_string[0:3]) # Pyt

# contains indices 1 and 3

print(py_string[1:5:2]) # yh

Output

Pyt
yh

In Python, list slicing is a common practice and it is the most used technique for programmers to solve efficient problems. Consider a python list, In-order to access a range of elements in a list, you need to slice a list. One way to do this is to use the simple slicing operator i.e. colon(:)

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.

Syntax:

Lst[ Initial : End : IndexJump ]

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.

Indexing

1. Positive Indexes

Below is a simple program, to
display a whole list using slicing.

Python3

Lst = [50, 70, 30, 20, 90, 10, 50]

print(Lst[::])

Output:

[50, 70, 30, 20, 90, 10, 50]

The above diagram illustrates a list Lst with its index values and elements.

2. Negative Indexes

Now, let us look at the below diagram which illustrates a list along with its negative indexes.

Index -1
represents the last element and -n represents the first element of the list(considering n as the length of the list). Lists can also be manipulated using negative indexes also.

Python3

Lst = [50, 70, 30, 20, 90, 10, 50]

print(Lst[-7::1])

Output:

[50, 70, 30, 20, 90, 10, 50]

The above program displays the whole list using the
negative index in list slicing.

3. Slicing

As mentioned earlier list slicing is a common practice in Python and can be used both with positive indexes as well as negative indexes. The below diagram illustrates the technique of list slicing:

The below program transforms the above illustration into python code:

Python3

Lst =
[50, 70, 30, 20, 90, 10, 50]

print(Lst[1:5])

Output:

[70, 30, 20, 90]

Below are some examples which depict the use of list slicing in Python:

Example 1:

Python3

List =
[1, 2, 3, 4, 5, 6, 7, 8, 9]

print("\nOriginal List:\n", List)

print("\nSliced Lists: ")

print(List[3:9:2])

print(List[::2])

print(List[::])

Output:

Original List:
 [1, 2, 3, 4, 5, 6, 7, 8, 9]

Sliced Lists: 
[4, 6, 8]
[1, 3, 5, 7, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Leaving
any argument like Initial, End or IndexJump blank will lead to the use of default values i.e 0 as Initial, length of list as End and 1 as IndexJump.

Example 2:

Python3

List = ['Geeks', 4, 'geeks !']

print("\nOriginal List:\n", List)

print("\nSliced Lists: ")

print(List[::-1])

print(List[::-3])

print(List[:1:-2])

Output:

Original List:
 ['Geeks', 4, 'geeks !']

Sliced Lists: 
['geeks !', 4, 'Geeks']
['geeks !']
['geeks !']

A reversed list can be generated by using a negative integer as the IndexJump argument. Leaving the Initial and End as blank. We need to choose the Initial and End value according to a reversed list if the IndexJump value is negative. 

Example 3:

Python3

List =
[-999, 'G4G', 1706256, '^_^', 3.1496]

print("\nOriginal List:\n", List)

print("\nSliced Lists: ")

print(List[10::2])

print(List[1:1:1])

print(List[-1:-1:-1])

print(List[:0:])

Output:

Original List:
 [-999, 'G4G', 1706256, '^_^', 3.1496]

Sliced Lists: 
[]
[]
[]
[]

If some slicing expressions are made that do not make sense or are incomputable then empty lists are generated.

Example 4:

Python3

List = [-999, 'G4G', 1706256, 3.1496, '^_^']

print("\nOriginal List:\n", List)

print("\nSliced Lists: ")

List[2:4] =
['Geeks', 'for', 'Geeks', '!']

print(List)

List[:6] = []

print(List)

Output:

Original List:
 [-999, 'G4G', 1706256, 3.1496, '^_^']

Sliced Lists: 
[-999, 'G4G', 'Geeks', 'for', 'Geeks', '!', '^_^']
['^_^']

List slicing can be used to modify lists or even delete elements from a list.

Example 5:

Python3

List =
[1, 2, 3, 4, 5, 6, 7, 8, 9]

print("\nOriginal List:\n", List)

print("\nSliced Lists: ")

newList = List[:3]+List[7:]

print(newList)

List =
List[::2]+List[1::2]

print(List)

Output:

Original List:
 [1, 2, 3, 4, 5, 6, 7, 8, 9]

Sliced Lists: 
[1, 2, 3, 8, 9]
[1, 3, 5, 7, 9, 2, 4, 6, 8]

By concatenating sliced lists, a new list can be created or even a pre-existing list can be modified. 

How do you slice a 2D array in Python?

To slice elements from two-dimensional arrays, you need to specify both a row index
and a column index as [row_index, column_index]
. For example, you can use the index [1,2] to query the element at the second row, third column in precip_2002_2013 .

Can you slice a list in Python?

In short, slicing is a flexible tool to build new lists out of an existing list. Python supports slice notation for any sequential data type like lists, strings, tuples, bytes, bytearrays, and ranges.

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 get an item from a 2D list Python?

Use list indexing to access elements in a 2D list. Use
the list indexing syntax a_2d_list[x][y] to access an element at index y in the nested list at index x .

Cara menggunakan python slice indices | admin | 4.5
shopee flash sale gratis ongkir
x