左からリスト要素を削除する

PythonPythonBeginner
今すぐ練習

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

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

はじめに

Pythonでは、スライス表記を使ってリストから要素を削除できます。このチャレンジでは、指定された数の要素をリストの左側から削除する関数を書く必要があります。


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-13625{{"左からリスト要素を削除する"}} python/lists -.-> lab-13625{{"左からリスト要素を削除する"}} python/tuples -.-> lab-13625{{"左からリスト要素を削除する"}} python/function_definition -.-> lab-13625{{"左からリスト要素を削除する"}} python/default_arguments -.-> lab-13625{{"左からリスト要素を削除する"}} end

左からリスト要素を削除する

drop(a, n=1) という関数を書きます。この関数は、リスト a とオプショナルな整数 n を引数として受け取り、元のリストの左から n 個の要素を削除した新しいリストを返します。n が指定されない場合、関数はリストの最初の要素のみを削除する必要があります。

def drop(a, n = 1):
  return a[n:]
drop([1, 2, 3]) ## [2, 3]
drop([1, 2, 3], 2) ## [3]
drop([1, 2, 3], 42) ## []

まとめ

このチャレンジでは、Pythonにおいてスライス表記を使ってリストから要素を削除する方法を学びました。また、指定された数の要素をリストの左側から削除する関数を書きました。