从左侧删除列表元素

Beginner

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

简介

在 Python 中,我们可以使用切片表示法从列表中删除元素。在这个挑战中,你需要编写一个函数,从列表的左侧删除指定数量的元素。

从左侧删除列表元素

编写一个函数 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 中从列表中删除元素。你还编写了一个函数,用于从列表的左侧删除指定数量的元素。