Fading Coder

One Final Commit for the Last Sprint

Home > Tools > Content

Python extend() Method Guide

Tools May 4 14

1. Basic Introduction

1.1 What is extend?

The extend method is a widely used term in many programming languages, typically referring to a method that extends or increases the number of elements in a collection such as objects, arrays, or lists. While the specific implementation and behavior may vary across languages, the core concept remains similar. Below is an introduction and usage example of the extend method in several common programming languages.

In Python, extend is a method of the list type, used to append all elements from an iterabel (e.g., list, tuple, set) to the end of the list.

Python extend illustration

1.2 Purpoce?

  • Append all elements of an iterable to the end of a list.
  • Unlike the + operator, extend modifies the original list in place, while + creates a new list.

1.3 Simple Example

# Create two lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]

# Use extend to merge lists
list1.extend(list2)

# Print the merged list
print(list1)  # Output: [1, 2, 3, 4, 5, 6]

2. Usage

2.1 Practical Application

In Python, if you want to add all elements from one list (e.g., loads["data"]["list"]) into another list (res["data"]["list"]), you should use the extend method instead of append. The append method adds the entire list as a single element, whereas extend adds each element individually.

2.2 Code Example

Code example illustration

Here's how to use the extend method:

# Assume res["data"]["list"] is already a list
# and loads is a dictionary with key "data", whose value is a dictionary containing key "list" with a list value

# Use extend to add elements from loads["data"]["list"] to res["data"]["list"]
res["data"]["list"].extend(loads["data"]["list"])

This way, res["data"]["list"] will contain all eelments from loads["data"]["list"], rather than having the latter as a single nested list element.

Related Articles

Installing CocoaPods on macOS Catalina (10.15) Using a User-Managed Ruby

System Ruby on macOS 10.15 frequently fails to build native gems required by CocoaPods (for example, ffi), leading to errors like: ERROR: Failed to build gem native extension checking for ffi.h... no...

Resolve PhpStorm "Interpreter is not specified or invalid" on WAMP (Windows)

Symptom PhpStorm displays: "Interpreter is not specified or invalid. Press ‘Fix’ to edit your project configuration." This occurs when the IDE cannot locate a valid PHP CLI executable or when the debu...

Capturing Android Screenshots and Screen Recordings with ADB

Two practical ways to grab images and videos from an Android device: Mirror the phone display to a computer and use desktop tools for screenshots and GIFs Use ADB commands (no UI mirroring required)...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.