bhylu.com

Advertisements

Add List Items

append, extend, and insert add values in different ways. Choose the method based on whether you have one object or an iterable of objects.

Understand the idea

append puts its argument in the list as a single item. extend consumes an iterable and adds its elements individually. insert places one object before a chosen position. In-place methods typically return None rather than the updated list.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

names = ["Mira"]
names.append("Dev")
names.extend(["Asha", "Noor"])
names.insert(0, "Leena")
print(names)

Read the result

The result is ['Leena', 'Mira', 'Dev', 'Asha', 'Noor'].

Try one change

Append a list to one copy and extend another copy with it. Compare the resulting shapes.