slice() スライスオブジェクト
最終更新:2026-09-22
slice() スライスオブジェクト
slice(stop) または slice(start, stop[, step]) はスライスオブジェクトを返す。list/tuple などの __getitem__ に使用する。
| カテゴリ | 組み込み関数 |
|---|---|
| 種類 | 組み込み関数 |
| Python バージョン | all |
📝 構文
slice(stop)
slice(start, stop[, step])
⚙️ 引数
| stop 必須 | The stop index (exclusive); in the one-arg form it is the slice endpoint. |
|---|---|
| start 任意 | The start index (inclusive); None when omitted.(デフォルト値:None) |
| step 任意 | The step; None when omitted.(デフォルト値:None) |
戻り値:A slice object with start/stop/step attributes, passable to __getitem__.
💥 例外
TypeError— Raised when an argument is not an integer (no __index__).
▶ 例
下のコードを編集し「実行」をクリックすると、出力パネルに結果が表示されます:
実行結果:
[1, 3]
💡 関連するケース
さらに多くのケースは近日公開予定です。
❓ よくある質問
Qslice(1, 5, 2) と lst[1:5:2] は同じ?
Aはい、lst[1:5:2] は内部で lst[slice(1, 5, 2)] を呼んでいます。slice オブジェクトは動的にスライスを構築する場合(スライス引数が設定やユーザー入力から来る場合など)に適しています。
Qslice オブジェクトの start/stop/step は必ず整数?
Aいいえ、None として省略できます。slice(5) の start と step はどちらも None で、「先頭からインデックス 5 まで」という意味になり、lst[:5] と一致します。
Qカスタムクラスでスライスをサポートするには?
A__getitem__(self, key) を実装し、key が slice オブジェクトの場合にその start/stop/step を解析して対応するロジックを適用します。
Qslice の引数は整数である必要がありますか?
Aはい。非整数(例:slice('a', 'b'))を渡すと TypeError になります。引数は __index__ を実装している必要があります。