Python Lists: Append vs. Extend - The List-Adding Logic!
Ever wondered why sometimes adding to a list results in a nested list, and other times it just merges elements? Let's clear up the confusion between `append()` and `extend()`!
Subject: Computer Science • Classes: 9–12 • Difficulty: advanced
The Trick
The core difference: `list.append(item)` adds its *entire argument* as a single element to the end of the list. If the argument is another list, it becomes a nested list. `list.extend(iterable)` iterates over its argument (which must be an iterable like a list, tuple, or string) and adds *each individual element* from that iterable to the end of the list. Think of `append()` as adding one 'thing' (even if that 'thing' is a box of other things), while `extend()` opens the 'box' and adds each item from inside it individually.
Mnemonic: Append: 'A'dd a single 'A'rgument. Extend: 'E'xtract and 'E'mbed 'E'lements.
Step-by-Step
- Understand `append()` — It treats whatever you pass to it as a single unit. If you pass `[1, 2]`, it adds `[1, 2]` as one element.
- Understand `extend()` — It expects an iterable (like another list, a tuple, or a string). It takes each item *from* that iterable and adds them one by one to your original list.
- Identify the Goal — If you want to add a whole collection as a single nested item, use `append()`. If you want to merge elements from one collection into another, use `extend()`.
Frequently Asked Questions
- Can I use `extend()` with a single number?
- No, `extend()` requires an iterable. `my_list.extend(5)` will cause an error because `int` is not iterable. You'd use `my_list.append(5)` instead.
- What if I `append()` a string?
- `my_list.append('hello')` will add `'hello'` as a single string element: `[..., 'hello']`. `my_list.extend('hello')` will add each character individually: `[..., 'h', 'e', 'l', 'l', 'o']`.
Study More with GyanAI
GyanAI is a free AI tutor for CBSE students. Ask any question for an instant step-by-step answer. Try GyanAI free.