リストの末尾から要素を削除する

PythonPythonBeginner
今すぐ練習

This tutorial is from open-source community. Access the source code

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

Python では、リストから要素を削除するにはさまざまな方法があります。そのような方法の 1 つは、リストの末尾から要素を削除することです。このチャレンジでは、リストの末尾から n 個の要素を削除する関数を作成します。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/default_arguments("Default Arguments") subgraph Lab Skills python/comments -.-> lab-13728{{"リストの末尾から要素を削除する"}} python/lists -.-> lab-13728{{"リストの末尾から要素を削除する"}} python/tuples -.-> lab-13728{{"リストの末尾から要素を削除する"}} python/function_definition -.-> lab-13728{{"リストの末尾から要素を削除する"}} python/default_arguments -.-> lab-13728{{"リストの末尾から要素を削除する"}} end

リストの末尾から要素を削除する

take_right(lst, n=1) という関数を作成します。この関数は、リスト lst とオプションの整数 n を引数として受け取り、リストの末尾から n 個の要素を削除した新しいリストを返します。n が指定されない場合、関数はリストの最後の要素のみを削除する必要があります。

この問題を解くには、リストの末尾から n 個の要素を取り出したスライスを作成するためにスライス表記を使用できます。

def take_right(itr, n = 1):
  return itr[-n:]
take_right([1, 2, 3], 2) ## [2, 3]
take_right([1, 2, 3]) ## [3]

まとめ

このチャレンジでは、Python のリストの末尾から要素を削除する方法を学びました。また、リストの末尾から n 個の要素を取り出したリストのスライスを作成するためにスライス表記をどのように使用するかも学びました。