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

本站现有博文340篇,共被浏览1019312次

本站已经建立2719天!

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