howtouselinux

4 Ways to Add Items to a List in Python

Table of Contents

Lists are a data structure that can contain multiple elements. These elements are ordered by the index which is beginning from zero. Additionally, lists are mutable—meaning they can be changed. The most common change to a list is adding to its elements. Here are four different ways to add items to an existing list.

Understanding list in Python

A Python list is a data structure that allows you to store multiple values in a single variable. This can be useful for storing data that you plan to iterate through or access randomly. Unlike arrays, which are fixed in size, Python lists can grow and shrink as needed.

This makes them an excellent choice for working with large datasets or when you don’t know how many items you will need to store. Lists are also easy to create and use. Here’s an example:

list = [ “apple” , “orange” , “banana” ]
print ( list ) # Output: [‘apple’, ‘orange’, ‘banana’]

 

Add Items to a list with List append() Method in Python

The best way to add items to a list in Python is to use append method. It will add a single item to the end of the existing list. The Python append() method only modifies the original list. It doesn’t return any value. The size of the list will increase by one.

It’s important to note that the append() method only adds a single item to the list. If you want to add multiple items, then either use the extend() method or perform several calls of append().

Adding data to the end of a list can be accomplished using the .append() method.

teams = [“Google”,”Amazon”,”Microsoft”]
teams.append(“Cisco”)
print(teams)
# [‘Google’, ‘Amazon’, ‘Microsoft’, ‘Cisco’]

Be careful when appending another list, as the result will be a nested list at the next available index.

teams = [“Google”,”Amazon”,”Microsoft”]
teams.append([“Cisco”, “Facebook”])
print(teams)
# [‘Google’, ‘Amazon’, ‘Microsoft’, [‘Cisco’, ‘Facebook’]]

Add Items to a list with List insert() Method in Python

The Python list insert() is an inbuilt method that inserts an element to the list at the specified index.  This method can be called only on list values. If the index is too high and out of range, the method places new value at the end of the list.

The syntax of the insert() method is list.insert(i, elem). Elem is inserted to the list at the ith index. All the elements after elem are shifted to the right.The insert() method doesn’t return anything; returns None. It only updates the current list.

Use the insert() method when you want to add data to the beginning or middle of a list. Take note that the index to add the new element is the first parameter of the method.

teams = [“Google”,”Amazon”,”Microsoft”]
teams.insert(0, “Cisco”)
print(teams)
# [‘Cisco’, ‘Google’, ‘Amazon’, ‘Microsoft’]

Add Items to a list with list extend() Method in Python

The extend() method adds all the elements of an iterable (list, tuple, string etc.) to the end of the list.

  • Syntax of List extend() – The syntax of the extend() method is:
  • list.extend(iterable) – all the elements of iterable are added to the end of list1.
  • extend() Parameters – the extend() method takes an iterable such as list, tuple, string etc.
  • Return Value from extend() – The extend() method modifies the original list. It doesn’t return any value.

 

If your goal is to combine two lists, then the .extend() method will append the supplied-list values to the end of the original list.

teams = [“Google”,”Amazon”,”Microsoft”]
teams.extend([“Cisco”, “Facebook”])
print(teams)
# [‘Google’, ‘Amazon’, ‘Microsoft’, ‘Cisco’, ‘Facebook’]

The supplied argument must be an iterable and will be treated as such, producing interesting results if not prepared.

teams = [“Google”,”Amazon”,”Microsoft”]
teams.extend(“Cisco”)
print(teams)
# [‘Google’, ‘Amazon’, ‘Microsoft’, ‘C’, ‘i’, ‘s’, ‘c’, ‘o’]

Add Items to a list with Plus Operator (+) in Python

A same technique to using the .extend() method is concatenating two lists with the plus-sign operator. There is little difference in performance between the two techniques; however, be aware that both operands must be lists, or a TypeError will be thrown.

first_list = [1,2,3]
second_list = [4,5,6]
print(first_list+second_list)
# [1, 2, 3, 4, 5, 6]

Difference between Python List append and Python List extend

When calling append method data will be appended as a single unit.
list1 = [1, 2, 3]
list2 = [3, 4, 5]
list1.append(list2)
# length of list1 will be 4 now.
print(list1) # should return [1, 2, 3, [3, 4, 5]]
print(len(list1)) # should return 4

# when calling extend method on list1, it appends elements in list 2 to the list 1
list1.extend(list2)
print(list1) #should return [1, 2, 3, 3, 4, 5]
print(len(list1)) #should return 6

# Another Example
list3 = [1, 2, 3]
list4 = [1, 2, 3]

list3.append(‘abc’) # will return [1, 2, 3, ‘abc’]
list4.extend(‘abc’)# will return [1, 2, 3, ‘a’, ‘b’, ‘c’]

 

Difference between Python List append and Python List insert

  • Python list .append([item]) appends Python elements to a Python lists whereas Python list .insert([index],[item]) inserts Python elements to Python lists. Python list insert method takes an additional argument for the Python index to place Python element in Python list.
  • Python list .insert() can be used when Python index is known, whereas Python list .append() could be used to append Python elements to end of a Python list.

How to Create a list in Python

There are several ways to create a Python list. The simplest is to use the built-in list() function:

list = list ()
# Creates an empty list
list.append ( “apple” ) # Adds an item to the end of the list
list.insert ( 0 , “orange” ) # Inserts an item at the beginning of the list
print ( list ) # Output: [‘orange’, ‘apple’, ‘banana’]

You can also create lists using comprehensions or generator expressions:
Comprehensions allow you to create lists by applying a filter or transforming one or more sequences. Here’s an example:
lists = [ i for i in range ( 20 )] # Create a list of the numbers 0-19
print ( lists ) # Output: [0, …,11 , 12 , 13 , 14 , 19 ]

You can also create lists by using concatenation or multiplication operators on sequences:
lists = [ “apple” ] * 50 + [ “orange” ] # Creates a list with 100 items (“apple”, then “orange”)
print ( lists ) # Output: [‘apple’, ‘apple’, …]

Finally, you can use the built-in list() function to convert any other iterable into a Python list:
lists = [ “apple” , “orange” ] # Create a string and turn it into a list of characters
print ( lists ) # Output: [‘apple’, ‘orange’]