Five Ways to Add Data to a List in Python

Five Ways to Add Data to a List in Python

Append, insert, extend, and more

Image for postPhoto by Hitesh Choudhary on Unsplash

Lists are a data structure that can contain multiple elements. These elements are ordered and represented by a nonnegative integer, beginning at zero.

Additionally, lists are mutable?meaning they can be changed. The most common change made to a list is adding to its elements.

Here are four different ways that data can be added to an existing list.

The .append() Method

Adding data to the end of a list is accomplished using the .append() method. If you are familiar with JavaScript, this method is the equivalent of .push().

teams = [ “Jaguars”, “Colts”, “Titans”]teams.append(“Texans”)print(teams)# [‘Jaguars’, ‘Colts’, ‘Titans’, ‘Texans’]

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

teams = [ “Jaguars”, “Colts”, “Titans”]teams.append([“Texans”, “Eagles”])print(teams)# [‘Jaguars’, ‘Colts’, ‘Titans’, [‘Texans’, ‘Eagles’]]

The .insert() Method

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 = [ “Jaguars”, “Colts”, “Titans”]teams.insert(0, “Texans”)print(teams)# [‘Texans’, ‘Jaguars’, ‘Colts’, ‘Titans’]

The .extend() Method

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 = [ “Jaguars”, “Colts”, “Titans”]teams.extend([“Texans”, “Eagles”])print(teams)# [‘Jaguars’, ‘Colts’, ‘Titans’, ‘Texans’, ‘Eagles’]

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

teams = [ “Jaguars”, “Colts”, “Titans”]teams.extend(“Texans”)print(teams)# [‘Jaguars’, ‘Colts’, ‘Titans’, ‘T’, ‘e’, ‘x’, ‘a’, ‘n’, ‘s’]

The Plus Operator (+)

A synonymous 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]


No Responses

Write a response