Python append list with string

How to Append a String to a List in Python

How to Append a String to a List in Python

Python lists are a common data type you’ll use to store data. Because they’re mutable (meaning they can be changed) and heterogeneous (meaning they can store different types of data), Python lists are very popular. Being able to add items to a list is a common operation. In this tutorial, you’ll learn how to append a string to a list in Python.

You may have tried to add a string to Python and saw some unexpected results. Perhaps, this is why you’re here! Well, look no further – you’ll learn all you need to know to be able to append a string to a list.

By the end of this tutorial, you’ll have learned the following:

  • How to append a string to a list in Python using different methods, such as .append() , .extend() , and .insert() and the + operator
  • Why appending a string to a list can lead to some unexpected results and how to prevent this
Читайте также:  Python классы методы примеры

How to Append a String to a List with Python with append

The best way to append a string to a list in Python is to use the list .append() method. This is because it most clearly expresses the intentions of the code and works without errors.

To see how to use the .append() method to add a string to a Python list, check out the example below. We use a list containing two strings, though this would work with other types of objects in the list as well.

# Append a String to a List in Python Using .append() values = ['welcome', 'to'] values.append('datagy') print(values) # Returns: # ['welcome', 'to', 'datagy']

In the example above, we used a simple use case to see how to add a string to a list. By passing a string into the .append() method, we were able to easily append the string.

Other List Methods to Append a String to a List

Python provides many different methods to append items to a list. In this section, we’ll explore three different methods that allow you to add a string to the end of a Python list:

How to Append a String to a List with Python with extend

The Python list.extend() method is used to add items from an iterable object to the end of a list. Because of this, we need to be careful, since Python strings themselves are iterable. Let’s see what happens when we try to add a string to a list using the .extend() method:

# Using .extend() to Append a String to a List values = ['welcome', 'to'] values.extend('datagy') print(values) # Returns: # ['welcome', 'to', 'd', 'a', 't', 'a', 'g', 'y']

We can see that this led to some unexpected results! Python unpacks the items in the string (since it’s iterable) and appends each item to the list. In order to prevent this behavior, we need to wrap the string in a list first:

# Using .extend() to Append a String to a List values = ['welcome', 'to'] values.extend(['datagy']) print(values) # Returns: # ['welcome', 'to', 'datagy']

We can see that by first wrapping the string in a list, that the issue was resolved. Keep in mind, however, that this is different than passing the string into the list() function, which would actually result in the same, unwanted result.

In the next section, you’ll learn how to use the .insert() method to append a string to a list.

How to Append a String to a List with Python with insert

The .insert() method allows you to pass an item into a list at a specific position. In order to append an item, we simply need to pass the string into the .insert() method at the last position.

# Using the .insert() Method to Append a String to a List values = ['welcome', 'to'] values.insert(len(values), 'datagy') print(values) # Returns: # ['welcome', 'to', 'datagy']

In the code block above, we use the .insert() method to append a string. Because we want to append the string, we pass in the position equal to the length of the list using the len() function.

How to Append a String to a List with Python with the + operator

Finally, let’s take a look at how we can use the + operator to add a string to the end of a list. Similar to the .extend() method, we need to add wrap the string in a list. If we don’t do this, each character in the string is appended individually. Let’s take a look at how this can be done:

# Using the + Operator to Append a String to a List values = ['welcome', 'to'] values += ['datagy'] print(values) # Returns: # ['welcome', 'to', 'datagy']

In the example above, we used the augmented assignment operator to simplify our code. In the following section, you’ll learn how to append a string to an empty list.

How to Append a String to an Empty List with Python

Appending a string to an empty list in Python works in the same way as with any other list. You can use any of the methods that we explored above. However, as mentioned the .append() method is the clearest way of accomplishing this.

# Append a String to an Empty List values = [] values.append('datagy') print(values) # Returns: # ['datagy']

The .append() method is incredibly clear in terms of what it’s doing. Because of this, it’s the method I recommend using.

How to Append a String to the Beginning a List with Python

Python provides a number of different ways to prepend an item to a list. The simplest way, in my opinion, is to use the .insert() method. While in the previous sections you learned how to add an item to the end of the list, it’s even simpler to add an item to the beginning of a list.

Let’s take a look at how to do this:

# Add a String to the Beginning of a List values = ['welcome', 'to'] values.insert(0, 'datagy') print(values) # Returns: # ['datagy', 'welcome', 'to']

In the code block above, we used the .insert() method to add an item at the 0 index position. Because Python lists are 0-based indexed, this represents the beginning of the list.

Conclusion

In this tutorial, you learned many different ways to append a string to a list in Python. Being able to work with lists and strings is an essential skill for any Python developer. You first learned how to use different methods to add a string to a list. While Python provides many different options, the .append() method is by far the clearest method.

Then, you learned how to append a string to an empty list. Finally, you learned how to prepend a string to a Python list, at the beginning of the list.

Additional Resources

To learn more about related topics, check out the tutorials below:

Источник

4 Ways to Append List in Python

Python is a versatile language that you can use for all sorts of purposes. One of the things that makes it so great is its ability to handle lists. Lists are one of the most basic data structures in Python, and they allow you to store multiple items in a single variable. In this blog post, we will discuss four different ways to append a list in Python.

Append list in Python

The best way to append 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.

  • With .append(), we can add a number, list, tuple, dictionary, user-defined object, or any other object to an existing list. However, we need to keep in mind that .append() adds only a single item or object at a time.
  • list.append() method is used for adding an item to the end of an existing list, without creating a new list.
  • When it is used for adding a list to another list, it creates a list within a list.
  • the element that you’re adding will be added to the end of the list. So, if you want to add an element to the beginning of a list, you’ll need to use a different method.

Syntax of Python list append method

  • SYNTAX – list_name.append(item)
  • PARAMETERS – The append() method takes a single item as an input parameter and adds that to the end of the list.
  • Return Value – The append() method only modifies the original list.

Append list with number in Python

To append a number to a list in Python, you will need to use the append() method. This method takes a single parameter, which is the number that you want to add to the list.In the code below we will check out how to add a new numeric item to a list.
Code:

>>># list of strings
>>>string_list = [‘Medium’,’Python’,’Machine Learning’,’Data Science’]
>>>#adding a new int item to the string_list
>>>string_list.append(1)
>>>#printing appended list
>>>print(string_list)

Output:
[‘Medium’,’Python’,’Machine Learning’,’Data Science’,’1’]

Append list with string in Python

The append() method can add string to the end of the list .

Here is an example:
characters = [‘Tokyo’, ‘Lisbon’, ‘Moscow’, ‘Berlin’]
characters.append(‘Nairobi’)
print(‘Updated list:’, characters)
Updated list: [‘Tokyo’, ‘Lisbon’, ‘Moscow’, ‘Berlin’, ‘Nairobi’]

Append list with a Single Item in Python

With .append(), you can add a number, list, tuple, dictionary, user-defined object, or any other object to an existing list. However, you need to keep in mind that .append() adds only a single item or object at a time:

>> x = [1, 2, 3, 4]
>>> y = (5, 6)
>>> x.append(y)
>>> x
[1, 2, 3, 4, (5, 6)]

Append new list to the list in Python

Apart from adding a string and a numeric data type, we can also add separate list to a list as below.

>>>#lets create a new list
>>>new_list = [1,2,3,4,5]
>>>#append this list to our string_list
>>>string_list.append(new_list)
>>># print the appended list
>>>string_list

We can see from the below output that a new list is appended at the end of our old list.
Output: [‘Medium’,’Python’,’Machine Learning’,’Data Science’,’1’,[1,2,3,4,5]]

We will get the whole list as an indexed item using the below code.
Code:
string_list[5]
Output:
[1,2,3,4,5]

Append list in for loop

Another common use case of .append() is to completely populate an empty list using a for loop. Inside the loop, we can manipulate the data and use .append() to add successive results to the list.

In the example below, we create an empty list and assign it to the variable num. Then, using a for loop, we add a sequence of elements (integers) to the list that was initially empty:
>> num = []
>>> for i in range(3, 15, 2):
num.append(i)

We check the value of the variable to see if the items were appended successfully and confirm that the list is not empty anymore:
>>> num
[3, 5, 7, 9, 11, 13]

FAQ about append list in Python

How does the append() method work?

The append() method works by adding the element to the end of the list. If the list is empty, then the append() method will create a new list and add the element to it.

understanding list index in Python

The list in Python is indexed. The elements in a list are indexed according to a definite sequence. The indexing of a list is starting with 0 being the first index and the last item index is n-1 where n is the number of items in a list.

Each element in the list has its indexed place in the list, which allows duplicating of elements in the list. We can create the same indexed item as another one with a different index and the list will still accept it.

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.

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’]

David is a Cloud & DevOps Enthusiast. He has years of experience as a Linux engineer. He had working experience in AMD, EMC. He likes Linux, Python, bash, and more. He is a technical blogger and a Software Engineer. He enjoys sharing his learning and contributing to open-source.

howtouselinux.com is dedicated to providing comprehensive information on using Linux.

We hope you find our site helpful and informative.

Источник

Оцените статью