python3

python でリストに、コロン演算子2つ(::)を使う

投稿日:2020年12月23日 更新日:

リストのコロンで指定できるパラメータには、「start, end, step」という意味がある。

以下の例では、:: 5 とした場合には、5 をステップとして、次に進んでいく。

::-5 とした場合には、5 をステップとして、前に戻っていく。

print('range(100)[::-5] の結果を表示')
for i in range(100)[::-5]:
    print(i, end=' ')

print('\nrange(100)[::-5] の結果を表示')
for i in range(100)[::5]:
    print(i, end=' ')
print('\n')

結果

range(100)[::-5] の結果を表示
99 94 89 84 79 74 69 64 59 54 49 44 39 34 29 24 19 14 9 4 
range(100)[::-5] の結果を表示
0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95

-python3
-,

執筆者:


comment

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

関連記事

no image

matplotlib で、x軸・y軸の目盛りを反対方向につけたい場合。

デフォルトでは、x軸はグラフの下に、y軸は左側につけられる。 例 import numpy as np from matplotlib import pyplot as plt x = np.lins …

no image

pythonで配列(リスト)の、ある要素がわかっているときにその次の要素を取得する方法。

リストを iter に変えたあと、… next() を使う。 参考リンク https://www.programiz.com/python-programming/methods/buil …

no image

python3 で辞書(dictionary)の一部を del で削除する

辞書の一部を削除するには、del で消去したいキーを指定する。 例 dict1 = {“名前”:”太郎”, “年齢”: 20, “住所”: “東京都千代田区大手町1-1”} print(dict1) …

no image

matplotlib でグラフ表示ウィンドウの画面上の位置を自由に設定する方法

matplotlib.use(‘TkAgg’) としておき、 get_current_fig_manager().window.wm_geometry(“+20+50”) として、(+20+50)のと …

no image

python3 で、リストを pop したものの返り値

リストを pop すると、 pop された値が返される。 例 plant_1 = [’pumpkin’, ‘ginger’, ‘potato’] plant_2 = [] print( …