Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Add an Element to a Python List at an Index?
1
How to Add an Element to a Python List at an Index?

To add an element to a given Python list, you can use either of the three following methods:

  1. Use the list insert method
    Code:
    list.insert(index, element)
    .


  2. Use slice assignment
    Code:
    lst[index:index] = [element]
    to overwrite the empty slice with a list of one element.


  3. Use list concatenation with slicing
    Code:
    lst[:2] + ['Alice'] + lst[2:]
    to create a new listobject.


In the following, you’ll learn about all three methods in greater detail. But before that, feel free to test those yourself in our interactive Python shell (just click “Run” to see the output):

https://trinket.io/embed/python/37221a165c

Method 1: insert(index, element)

The
Code:
list.insert(i, element)
method adds an element
Code:
element
to an existing
Code:
list
at position
Code:
i
. All elements
Code:
j>i
will be moved by one index position to the right.

Here’s an example with comments:

Code:
# Create the list lst = [2, 4, 6, 8] # Insert string at index 2 lst.insert(2, 'Alice') # Print modified list object print(lst) # [2, 4, 'Alice', 6, 8]

Properties of
Code:
insert()


Operates on existing list object

Simple

Fast

Check out the objects in memory while executing this code snippet (in comparison to the other methods discussed in this article):

https://pythontutor.com/iframe-embed.htm...nces=false

Click “Next” to move on in the code and observe the memory objects creation.

Related article: Python List insert() Method

Method 2: Slice Assignment

Slice assignment is a little-used, beautiful Python feature to replace a slice with another sequence.

Simply select the slice you want to replace on the left and the values to replace it on the right side of the equation.

For example, the slice assignment
Code:
list[2:4] = [42, 42]
replaces the list elements with index
Code:
2
and
Code:
3
with the value
Code:
42
.

Here’s another example that shows you how to insert the string
Code:
'Alice'
into a list with four integers.

[Image: sliceAssignment-1024x576.jpg]

Let’s have a look at the code:

Code:
# Create the list lst = [2, 4, 6, 8] # Insert string at index 2 lst[2:2] = ['Alice'] # Print modified list object print(lst) # [2, 4, 'Alice', 6, 8]

Properties of Slice Assignment

Operates on existing list object

Slightly more complex

Fast

Related article: Python Slice Assignment

Method 3: List Concatenation

If you use the
Code:
+
operator on two integers, you’ll get the sum of those integers. But if you use the
Code:
+
operator on two lists, you’ll get a new list that is the concatenation of those lists.

Here’s the same example, you’ve already seen in the previous sections:

Code:
# Create the list lst = [2, 4, 6, 8] # Insert string at index 2 lst = lst[:2] + ['Alice'] + lst[2:] # Print modified list object print(lst) # [2, 4, 'Alice', 6, 8]

Properties of List Concatenation

Creates a new list object

Slightly more complex

Slower

Related article: How to Concatenate Lists in Python? [Interactive Guide]

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: