EADST

Python list 列表删除元素

# ============================================
# Python list 列表删除元素(4种方法)
# 作者:XD
# 日期:2025-10-11
# ============================================

# 在 Python 中删除列表元素常见有 4 种方式:
# 1. 使用 del 按索引删除
# 2. 使用 pop() 按索引删除并返回元素
# 3. 使用 remove() 按值删除
# 4. 使用 clear() 清空整个列表


# ------------------------------------------------
# 1. del:根据索引值删除元素
# ------------------------------------------------
# del 是 Python 的关键字,用于删除变量或列表中的元素
# 语法:
# del listname[index]       # 删除单个元素
# del listname[start:end]   # 删除连续的一段元素

lang = ["Python", "C++", "Java", "PHP", "Ruby", "MATLAB"]

# 删除索引为 2 的元素(Java)
del lang[2]
print(lang)

# 删除倒数第二个元素(Ruby)
del lang[-2]
print(lang)

# 删除一段连续的元素(索引 1 到 3,不包含 4)
lang = ["Python", "C++", "Java", "PHP", "Ruby", "MATLAB"]
del lang[1:4]
print(lang)

# 扩展列表后删除一段负索引范围
lang.extend(["SQL", "C#", "Go"])
del lang[-5:-2]
print(lang)


# ------------------------------------------------
# 2. pop():根据索引值删除元素,并返回该元素
# ------------------------------------------------
# 语法:
# listname.pop(index)
# 如果不写 index 参数,则默认删除最后一个元素(类似“出栈”)

nums = [40, 36, 89, 2, 36, 100, 7]

# 删除索引为 3 的元素
nums.pop(3)
print(nums)

# 删除最后一个元素
nums.pop()
print(nums)

# pop() 通常与 append() 搭配使用,形成“栈”操作
# append() 相当于“入栈”,pop() 相当于“出栈”


# ------------------------------------------------
# 3. remove():根据元素值进行删除
# ------------------------------------------------
# 语法:
# listname.remove(value)
# remove() 方法只会删除第一个匹配到的值,若不存在则报错

nums = [40, 36, 89, 2, 36, 100, 7]

# 第一次删除 36
nums.remove(36)
print(nums)

# 第二次删除 36
nums.remove(36)
print(nums)

# 删除不存在的元素(会报错)
# nums.remove(78)   # ValueError: list.remove(x): x not in list

# 建议在使用 remove() 前先判断元素是否存在
if 78 in nums:
    nums.remove(78)
else:
    print("元素 78 不在列表中,无法删除。")


# ------------------------------------------------
# 4. clear():清空整个列表
# ------------------------------------------------
# 语法:
# listname.clear()
# 清除所有元素,相当于将列表重置为空

url = list("http://c.biancheng.net/python/")
url.clear()
print(url)  # 输出:[]


# ------------------------------------------------
# ✅ 四种方法对比总结:
# ------------------------------------------------
# | 方法      | 删除依据 | 是否返回值 | 可删除范围 | 错误情况 |
# |------------|-----------|-------------|-------------|-----------|
# | del        | 索引     | 无          | 单个或连续元素 | 索引越界 |
# | pop()      | 索引     | 有(被删元素) | 单个元素 | 索引越界 |
# | remove()   | 元素值   | 无          | 单个匹配值 | 元素不存在 |
# | clear()    | 无       | 无          | 全部元素 | 无 |

# ------------------------------------------------
# 使用建议:
# - 需要保留被删除的值 → 用 pop()
# - 需要按值删除 → 用 remove()
# - 删除一段或全部 → 用 del / clear()
# ------------------------------------------------

相关标签
About Me
XD
Goals determine what you are going to be.
Category
标签云
YOLO PDB Michelin 财报 InvalidArgumentError RL Translation Harness FlashAttention Claude MD5 BF16 API Bert Clash Qwen2.5 TensorRT diffusers 强化学习 NLP Food Windows Bin Image2Text PyTorch OpenAI 第一性原理 WAN Tiktoken CEIR GIT Jev CLAP Transformers RGB Distillation NameSilo Nginx Vim logger Pillow Shortcut CUDA UNIX Conda FP16 GoogLeNet SQLite printf Anaconda CC v0.dev GPTQ CSV TSV Llama Vmess DeepStream UI FP8 Interview FP32 LLAMA Excel Data Baidu Python CTC Quantization torchinfo 搞笑 llama.cpp Git PIP Use BeautifulSoup FP64 关于博主 transformers Magnet uWSGI Datetime Tensor 域名 腾讯云 tar IndexTTS2 Tracking 论文速读 VSCode GPT4 HuggingFace HaggingFace 继承 Rebuttal Knowledge COCO Django Safetensors Input CV QWEN Website C++ Google Qwen Video Logo Firewall Proxy Crawler API网关 Jetson Qwen2 OpenCV 自我改进 Bitcoin Ubuntu LLM News Freesound 图形思考法 Ptyhon Docker 顶会 EXCEL Breakpoint SVR git-lfs 证件照 Dataset LeetCode 云服务器 AI 论文 Markdown VPN Statistics Disk RAR GGML Linux LaTeX 净利润 Github 算法题 git 签证 Agent 多进程 mmap Paddle Plate PyCharm scipy Permission ms-swift SPIE Attention XGBoost Gemma Math ChatGPT Augmentation Zip ModelScope Color 版权 多线程 FastAPI SAM WebCrawler Plotly ONNX Search 公式 长期记忆 icon Template Hotel 阿里云 JSON TensorFlow v2ray Quantize Jupyter PDF Pandas Review Pytorch Land Pickle Mixtral Sklearn BTC 递归学习法 飞书 CAM OCR Heatmap TTS LoRA Animate Cloudreve Random hf Paper ResNet-50 tqdm Diagram SQL Password NLTK DeepSeek Hilton 报税 图标 Streamlit 音频 Domain Hungarian Base64 Miniforge Algorithm Web XML Card Numpy Bipartite VGG-16 uwsgi
站点统计

本站现有博文339篇,共被浏览1002213次

本站已经建立2712天!

热门文章
文章归档
回到顶部