LoginSignup
0
0

PythonのSliceの使い方

Last updated at Posted at 2024-02-13

仕事でよくPythonを使うので、最近改めてPythonを勉強し直しています。
PythonのSliceが便利だったので備忘録としてまとめます。

また、この記事ではリストについて書いていますが、タプルでも同様に扱えます。

使い方① リストから任意の範囲の要素をすべて取得

以下のように書くことで、Sliceを使うことでリストから任意の範囲の要素を取得することができます。

list1 = ["a", "b", "c", "d", "e", "f", "g", "h"]

list2 = list1[2:7]
print(list2) # c d e f gが表示される

使い方② リストから任意の範囲の要素を任意の間隔で取得

以下のように書くことで、リストの任意の範囲の要素を任意の間隔で取得することもできます

list1 = ["a", "b", "c", "d", "e", "f", "g", "h"]

list2 = list1[2:7:2]
print(list2) # c e g が表示される

使い方③ リストから先頭または末尾から任意の数の要素を取得

list1 = ["a", "b", "c", "d", "e", "f", "g", "h"]

list2 = list1[:4]
print(list2) # a b c d が表示される

list3 = list1[5:]
print(list3) # e f g h が表示される

list4 = list1[:4:2]
print(list4) # a c が表示される

list5 = list1[5::2]
print(list5) # e g が表示される

上記のように先頭や末尾からデータを取り出す際も、任意の間隔を指定することができます。

使い方④ リストを反転する

以下のように書くことでリストの順序を反転することもできます。

list1 = ["a", "b", "c", "d", "e", "f", "g", "h"]

list2 = list1[::-1]
print(list2) # h g f e d c b a が表示される

以上となります。


【宣伝】
Next.jsを使って技術系ブロクを作りました。
めちゃくちゃのんびり投稿しているので記事は少ないですが、よかったら見てやってください。
こちら

https://www.nattomatofu.com/

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0