Cara menggunakan python implement indexing

In this lesson, you’ll see how to access individual elements and sequences of objects within your lists. Lists elements can be accessed using a numerical index in square brackets:

This is the same technique that is used to access individual characters in a string. List indexing is also zero-based:

>>>

>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster'] >>> a ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster'] >>> a[0] 'spam' >>> a[2] 'bacon' >>> a[5] 'lobster' >>> a[len(a)-1] 'lobster' >>> a[6] Traceback (most recent call last): File "<input>", line 1, in <module> a[6] IndexError: list index out of range

List elements can also be accessed using a negative list index, which counts from the end of the list:

>>>

>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster'] >>> a[-1] 'lobster' >>> a[-2] 'ham' >>> a[-5] 'egg' >>> a[-6] 'spam' >>> a[-len(a)] 'spam' >>> a[-8] Traceback (most recent call last): File "<input>", line 1, in <module> a[-8] IndexError: list index out of range

Slicing is indexing syntax that extracts a portion from a list. If a is a list, then a[m:n] returns the portion of a:

  • Starting with postion m
  • Up to but not including n
  • Negative indexing can also be used

Here’s an example:

>>>

>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster'] >>> a[2:5] ['bacon', 'tomato', 'ham'] >>> a[-5:-2] ['egg', 'bacon', 'tomato'] >>> a[1:4] ['egg', 'bacon', 'tomato'] >>> a[-5:-2] == a[1:4] True

Omitting the first and/or last index:

  • Omitting the first index a[:n] starts the slice at the beginning of the list.
  • Omitting the last index a[m:] extends the slice from the first index m to the end of the list.
  • Omitting both indexes a[:] returns a copy of the entire list, but unlike with a string, it’s a copy, not a reference to the same object.

Here’s an example:

>>>

>>> a ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster'] >>> a[:4] ['spam', 'egg', 'bacon', 'tomato'] >>> a[0:4] ['spam', 'egg', 'bacon', 'tomato'] >>> a[2:] ['bacon', 'tomato', 'ham', 'lobster'] >>> a[2:len(a)] ['bacon', 'tomato', 'ham', 'lobster'] >>> a ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster'] >>> a[:] ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster'] >>> a == a[:] True >>> a is a[:] False >>> s = 'mybacon' >>> s[:] 'mybacon' >>> s == s[:] True >>> s is s[:] True

A stride can be added to your slice notation. Using an additional : and a third index designates a stride (also called a step) in your slice notation. The stride can be either postive or negative:

>>>

>>> a ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster'] >>> a[0:6:2] ['spam', 'bacon', 'ham'] >>> a[1:6:2] ['egg', 'tomato', 'lobster'] >>> a[6:0:-2] ['lobster', 'tomato', 'egg'] >>> a ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster'] >>> a[::-1] ['lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam']

Postingan terbaru

LIHAT SEMUA