AMZ DIGICOM

Digital Communication

AMZ DIGICOM

Digital Communication

Python add to list – IONOS

PARTAGEZ

Lists are fundamental data structures in computer science. Many algorithms rely on list modification. This is how you can add elements to a list in Python.

How to add elements to a Python list?

Unlike tuples and strings, Python lists are “mutable”, that is, data structures that can be modified. It is possible to add elements to a Python list, delete them, or even modify their order. There are different approaches to this, each with its own advantages and disadvantages.

We let us present the following four approaches to add elements to a list in Python:

  1. Add Elements to a Python List Using Python Methods-list;
  2. Add elements to a Python list with list concatenation;
  3. Add elements to a Python list with Slice-Notation;
  4. Add elements to a Python list with List Comprehension.

Add elements to a list with Python-list methods

In Python, the class listserves as the basis for all list operations. The class defines a series of methods for list objects. This includes three methods that are suitable for adding items to a list:

method list arguments explanation
append() element Add a single item to the end of the list
extend() [elements] Add multiple items to the end of the list
insert() index, element Add a single element before the given index

It is important to understand that the modification is carried out “on site” for the three methods mentioned. This means that we modify the list object instead of creating and returning a new list. Therefore, all these methods return None:

primes = [2, 3, 5, 7]
# Append additional prime number, saving returned result
should_be_none = primes.append(11)
# Show that the prime was added
assert primes == [2, 3, 5, 7, 11]
# Show that `None` was returned
assert should_be_none is None

Python

Add a single element to the end of the list with append()

The Python method-append()allow to add a single element to the end of an existing list. Here is an example to illustrate it:

# List containing single prime number
primes = [2]
# Add an element to the end of the list
primes.append(3)
# Show that the element was added
assert primes == [2, 3]

Python

Be careful when using append(): the method always add only one element. If the element to add is another list, we obtain a nested list:

# List with two prime numbers
primes = [2, 3]
# Try to appends multiple numbers at once
primes.append([5, 7])
# Accidentally created a nested list
assert primes == [2, 3, [5, 7]]

Python

Our attempt to create the list [2, 3, 5, 7]failed. To add several elements, it is better to use the method extend().

Add elements to end of list with extend()

The Python method-extend()works the same as the method append()with the only difference that multiple items are added to an existing list. Let’s return to the previous example to better understand:

# List containing single prime number
primes = [2]
# Extend list by two elements
primes.extend([3, 5])
# Show that both element were added
assert primes == [2, 3, 5]

Python

Be careful though: the method extend()waits an iterable as argument and unpacks its elements. This can lead to surprising output when calling a string:

# List of friends
friends = [‘Mary’, ‘Jim’]
# Try to extend by additional friend
friends.extend(‘Jack’)
# String is unpacked into individual letters
assert friends == [‘Mary’, ‘Jim’, ‘J’, ‘a’, ‘c’, ‘k’]

Python

To add a single element to a Python list, we use either append()either we enclose the element in a list with brackets. In this case, the call for extend()also works:

# List of friends
friends = [‘Mary’, ‘Jim’]
# Extend by additional friend inside list
friends.extend([‘Jack’])
# Show that it worked
assert friends == [‘Mary’, ‘Jim’, ‘Jack’]

Python

Use insert() to add a single element before the specified index

So far we have shown how to add one or more elements to the end of a Python list. But what if we want insert an element at a specific location ? This is precisely what the Python method is all about-insert(). This takes into account a numerical index in addition to the element to be inserted:

# List of friends
friends = [‘Mary’, ‘Jim’, ‘Jack’]
# Insert additional friend `"Molly"` before index `2`
friends.insert(2, ‘Molly’)
# Show that "Molly" was added
assert friends == [‘Mary’, ‘Jim’, ‘Molly’, ‘Jack’]

Python

Be careful when trying to add multiple items with insert(): as insert()adds exactly one element, this necessarily results in the creation of a nested list :

# List of friends
friends = [‘Mary’, ‘Jim’]
# Try to insert multiple friends at once
friends.insert(1, [‘Molly’, ‘Lucy’])
# Accidentally created a nested list
assert friends == [‘Mary’, [‘Molly’, ‘Lucy’], ‘Jim’]

Python

For correctly insert multiple items into a listyou have to go through a loop for. We also use the function reversed()to preserve the order of inserted elements:

# List of friends
friends = [‘Mary’, ‘Jim’]
# Using `reversed()` keeps order of inserted elements
for friend in reversed([‘Molly’, ‘Lucy’]):
  friends.insert(1, friend)

# Show that it worked
assert friends == [‘Mary’, ‘Molly’, ‘Lucy’, ‘Jim’]

Python

Add elements to a list using Python list concatenation

In addition to the methods listseen above, it is possible to make a list concatenation to add elements to a Python list. In this case, we use the Python operator +. Concatenating lists roughly corresponds to using the method extend()with the difference that concatenation creates a new list instead of modifying the list “in place”.

As an example, let’s create two lists and add the second to the first. As the operation returns a new listthe return value is assigned to a new list:

# List of guys
guys = [‘Jim’, ‘Jack’]
# List of gals
gals = [‘Molly’, ‘Mary’]
# Concatenate both lists
folks = guys + gals
# Show that it worked
assert folks == [‘Jim’, ‘Jack’, ‘Molly’, ‘Mary’]

Python

Background, the concatenation operator calls the method __add__(). The expressions guys + galsAnd guys.__add__(gals)are equivalent here:

# Show that both expressions return the same result
assert guys + gals == guys.__add__(gals)

Python

If you are familiar with Python operators, you may already suspect this: list concatenation also supports augmented assignment. We use the operator +=To add items to an “in-place” list:

# Shopping list
groceries = [‘Milk’, ‘Bread’, ‘Eggs’]
# Add butter
groceries += [‘Butter’]
# Show that it worked
assert groceries == [‘Milk’, ‘Bread’, ‘Eggs’, ‘Butter’]

Python

The operator +=calls the method __iadd__(), where the “i” stands for “in-place”. As for the method extend(), the receiver of the method is modified directly. The following lines are therefore equivalent:

  • groceries = groceries + [‘Butter’]
  • groceries += [‘Butter’]
  • groceries.__iadd__([‘Butter’])
  • groceries.extend([‘Butter’])

It’s best to be careful when using list concatenation operators to add a single element. A unique element must also be contained in a listotherwise there is a risk of iterable decompression:

# List of cities
cities = [‘London’, ‘Paris’]
# Attempt to add city; likely not what you intended
cities += ‘Rome’
# String is unpacked into individual letters
assert cities = [‘London’, ‘Paris’, ‘R’, ‘o’, ‘m’, ‘e’]

Python

Using a single-element list will likely add an additional city to the list:

# List of cities
cities = [‘London’, ‘Paris’]
# Create a single-element list
cities += [‘Rome’]
# Now the entire string is added
assert cities = [‘London’, ‘Paris’, ‘Rome’]

Python

Add Elements to a List in Python with the Slice Operator

The Slices are a Python function that allows you to select elements of a list that follow one another. Slice’s syntax corresponds to the famous function range():

# The `slice()` function constructs a new `slice` object
slice(start, stop, step=1)

Python

It also exists a shorthand notation for creating Slice objects in combination with the index operator []:

# Select items of list
lst[start:stop:step]

Python

A Slice object can be used instead of a numeric index to select multiple elements of a sequence:

people = [‘Jim’, ‘John’, ‘Mary’, ‘Jack’]
# Select elements between index `1` (inclusive) and `3` (exclusive)
assert people[1:3] == [‘John’, ‘Mary’]
# Select every other element
assert people[::2] == [‘Jim’, ‘Mary’]

Python

In combination with assignmentsSlices can be used as an alternative to methods list()append(), extend()And insert():

Method list Corresponding Slice Operator Explanation
lst.append(element) lst[len(lst)+1 :] = [element] Add an item to the end of a list
lst.extend([elements]) lst[len(lst)+1 :] = [elements] Add multiple items to the end of a list
lst.insert(index, element) lst[index:index] = [element] Add an element before the given index

To understand how it works, let’s first see how to assign a list item by numeric index. Only one element of the list is then deleted:

# List of groceries
groceries = [‘Milk’, ‘Bread’, ‘Eggs’]
# Overwrite element at index `1`
groceries[1] = ‘Fruit’
# Show that it worked
assert groceries == [‘Milk’, ‘Fruit’, ‘Eggs’]

Python

What to do now if we seek to insert element by index assignment ? We use a Slice which contains the desired index as value startAnd stop. For the Slice assignment to work, you absolutely need a list to the right of the equal sign:

# List of groceries
groceries = [‘Milk’, ‘Bread’, ‘Eggs’]
# Insert element before index `1`
groceries[1:1] = [‘Fruit’]
# Show that it worked
assert groceries == [‘Milk’, ‘Fruit’, ‘Bread’, ‘Eggs’]

Python

This trick even allows insert multiple elements at once into a Python listwhich is impossible with the method insert():

# List of groceries
groceries = [‘Milk’, ‘Bread’, ‘Eggs’]
# Insert elements before index `1`
groceries[1:1] = [‘Fruit’, ‘Butter’]
# Show that it worked
assert groceries == [‘Milk’, ‘Fruit’, ‘Butter’, ‘Bread’, ‘Eggs’]

Python

Slice assignments allow you to selectively clear items from a list. Overall, Slice remains a very flexible method that has a place in the toolbox of anyone developing in Python.

Add Python Elements to a List with List Comprehension

A common way in Python to add elements to a list is to populate a new list with items. The standard approach, which works in Python as in most programming languages, is:

  1. Create an empty list;
  2. Create looping elements;
  3. Extend the list with the created item.

As an example, let’s see how generate the list of the first ten squares :

# Empty list to be filled
squares = []
# Successively create numbers 0..9
for n in range(10):
  # Compute squared number
  squared = n * n
  # Append squared number to list
  squares.append(squared)

# Show that it worked
assert squares == [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Python

There is, however, a better approach in Python. We use what is called a List Comprehension to create the list without looping fornor empty list variable:

# Create first ten square numbers
squares = [n ** 2 for n in range(10)]
# Show that it worked
assert squares == [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Python

Despite their elegance, List Comprehensions are only suitable for filling a new list. To extend an existing list, you must use the methods explained above.

With Deploy Now by IONOS, deploy your websites and apps with GitHub!

Télécharger notre livre blanc

Comment construire une stratégie de marketing digital ?

Le guide indispensable pour promouvoir votre marque en ligne

En savoir plus

Souhaitez vous Booster votre Business?

écrivez-nous et restez en contact