Python Guide Sidebar

Add Items to a Python List

Introduction

Adding items to a list is a core operation in Python. Lists are dynamic, allowing developers to modify them by appending, inserting, or extending their content. Understanding these methods can significantly improve your code’s performance and readability.

Methods to Add List Items

1. Append Items

The append() method adds a single element to the end of the.

Syntax:

list.append(item)

Example:

my_list = [1, 2, 3]
print(my_list) 
my_list.append(4)
print(my_list) 
2. Insert Items

The insert() method adds an element at a specified index.

Syntax:

list.insert(index, item)

Example:

my_list = [1, 2, 4]
print(my_list) 
my_list.insert(2, 3)  
print(my_list) 

3. Extend

The extend() method adds elements from another iterable to the end .

Syntax:

list.extend(iterable)

Example:

my_list = [1, 2, 3]
print(my_list) 
my_list.extend([4, 5])
print(my_list) 

4. Add Any Iterable

The extend() method can also work with tuples, sets, or strings.

Example:

my_list = [1, 2]
print(my_list) 
my_list.extend((3, 4)) 
print(my_list) 

Interview Questions


1. How do you append an item to a Python list? (Google)

Answer:

Use the append() method to add a single item .

my_list = [1, 2, 3]
my_list.append(4)
print(my_list) 

2. What is the difference between append() and extend()?(Amazon)

Answer:

  • append() add item.
  • extend() add item.

3. How do you insert an element at a specific index?(Microsoft)

Answer:

Use the insert() method, specifying the index and the element.

my_list = [1, 2, 4]
print(my_list) 
my_list.insert(2, 3)  
print(my_list) 

4. How can you add elements from a tuple to a list? (Meta)

Answer:

Use the extend() method to add elements from a tuple.

my_list = [1, 2]
print(my_list) 
my_list.extend((3, 4)) 
print(my_list)  

5. What happens if you use insert() with a negative index?(IBM)

Answer:

It inserts the element at the specified position counting from the end .


Quizz time with Adding Python Lists