Python append and return

The append() Function in Python

Python supports object-oriented programming and has concise, readable, and easy-to-learn syntax. It is no wonder that it is one of the most popular programming languages. Python has the function append() built-in.

We’ve written a series of articles to help you learn and brush up on the most useful Python functions. We’ll learn more about this append() function in Python and how to use it in this article.

If you are preparing for a tech interview, check out our technical interview checklist, interview questions page, and salary negotiation e-book to get interview-ready! Also, read Python String join() Method, Python Exit commands, and Type and Isinstance In Python for more content on Python coding interview preparation.

Having trained over 10,000 software engineers, we know what it takes to crack the toughest tech interviews. Our alums consistently land offers from FAANG+ companies. The highest ever offer received by an IK alum is a whopping $1.267 Million!

Читайте также:  Java сложение комплексных чисел

At IK, you get the unique opportunity to learn from expert instructors who are hiring managers and tech leads at Google, Facebook, Apple, and other top Silicon Valley tech companies.

Want to nail your next tech interview? Sign up for our FREE Webinar.

In this article, we’ll cover:

  • What Is the append() Function In Python and What Does It Do?
  • The append() Function in Python: Syntax
  • The append() Function in Python: Example
  • FAQs on The append() Function in Python

What Is the append() Function in Python and What Does It Do?

The append() function in Python takes a single item as an input parameter and adds it to the end of the given list. In Python, append() doesn’t return a new list of items; in fact, it returns no value at all. It just modifies the original list by adding the item to the end of the list.

After executing append() on a list, the size of the original list increases by one. The item in the list can be a string, number, dictionary, or even another list (because a list is an object too). When a list is appended onto the original list, it is added as a single object. The addition of the appended list happens, as usual, at the end of the original list.

The append() Function in Python: Syntax

  • Parameters: item is the only parameter append() takes, and it is the item to be added at the end of the list.
  • Returns: append() doesn’t return any value. It just adds the item to the end of the list.

The append() Function in Python: Example

Here, we take a look at how to use the append() function in Python next time you need it:

How to Use the append() Function in Python

Code to Append an Item to the List Using append()

 # Add a string element to the string list: stringList = ['mon', 'tue', 'wed', 'thu'] print(stringList) stringList.append('fri') print(stringList) # Add an int element to the string list: stringList.append(8) print(stringList) # Add an int element to the int list: intList = [0, 2, 4, 6] print(intList) intList.append(8) print(intList) # Add a string element to the int list: intList.append('fri') print(intList) 

Note: The code is for Python 3.x, but the same code will run in Python 2.x, with just the print syntax changed to print listName instead of print(listName).

Output
 ['mon', 'tue', 'wed', 'thu'] ['mon', 'tue', 'wed', 'thu', 'fri'] ['mon', 'tue', 'wed', 'thu', 'fri', 8] [0, 2, 4, 6] [0, 2, 4, 6, 8] [0, 2, 4, 6, 8, 'fri'] 


Code to Append a List Onto a List Using append()

 # Appending a list as an item onto the original list stringList = ['mon', 'tue', 'wed', 'thu', 'fri'] print(stringList) listToAppend = ['sat', 'sun'] print(listToAppend) # Appending listToAppend onto stringList stringList.append(listToAppend) print(stringList) # We can access the elements from the appended list in the same way we access elements from a 2-D Matrix. print(stringList[5][0]) print(stringList[5][1]) 
Output
 ['mon', 'tue', 'wed', 'thu', 'fri'] ['sat', 'sun'] ['mon', 'tue', 'wed', 'thu', 'fri', ['sat', 'sun']] sat sun 

Found this article helpful? You can learn about more Python functions in our learn folder.

FAQs on the append() Function in Python

Q1. How can we append to a list in Python?

You can use extend(), append(), and itertools.chain() depending on your needs to append to a list in Python.

Q2. What’s the difference between the insert() and append() functions in Python?

In Python, insert() allows you to insert an element to the list at any index of your choice. In contrast, append() appends the element only at the end of the list.

Q3. What’s the difference between the extend() and append() functions in Python?

Unlike append() in Python, which adds a single element to the end of the list, extend() iterates over its parameter, adds each element to the list and extends the list.

Q4. Does append() function in Python make a copy of the list?

No. append() modifies the original list. It does not create a copy of the list.

Q5. What parameters does the append() function in Python take, and what does it return?

Python’s append() function takes a single parameter, the item to append. It returns no value or list as it modifies the original list by appending the item at the end of the list.

Ready to Nail Your Next Coding Interview?

Whether you’re a coding engineer gunning for a software developer or software engineer role, a tech lead, or you’re targeting management positions at top companies, IK offers courses specifically designed for your needs to help you with your technical interview preparation!

If you’re looking for guidance and help with getting started, sign up for our FREE webinar. As pioneers in the field of technical interview preparation, we have trained thousands of software engineers to crack the toughest coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!

Источник

Python List Append – How to Add an Element to an Array, Explained with Examples

Estefania Cassingena Navone

Estefania Cassingena Navone

Python List Append – How to Add an Element to an Array, Explained with Examples

Welcome

Hi! If you want to learn how to use the append() method, then this article is for you. This is a powerful list method that you will definitely use in your Python projects.

In this article, you will learn:

  • Why and when you should use append() .
  • How to call it.
  • Its effect and return value.
  • How it can be equivalent to insert() and string slicing with the appropriate arguments.

You will find examples of the use of append() applied to strings, integers, floats, booleans, lists, tuples, and dictionaries.

Let’s begin! ✨

🔹 Purpose

With this method, you can add a single element to the end of a list.

Here you can see the effect of append() graphically:

image-59

💡 Tip: To add a sequence of individual elements, you would need to use the extend() method.

🔸 Syntax & Parameters

This is the basic syntax that you need to use to call this method:

image-60

💡 Tip: The dot is very important since append() is a method. When we call a method, we use a dot after the list to indicate that we want to «modify» or «affect» that particular list.

As you can see, the append() method only takes one argument, the element that you want to append. This element can be of any data type:

  • Integer
  • String
  • Float
  • Boolean
  • Another list
  • Tuple
  • Dictionary
  • An Instance of a custom class

Basically, any value that you can create in Python can be appended to a list.

💡 Tip: The first element of the syntax (the list) is usually a variable that references a list.

Example

This is an example of a call to append() :

>>> musical_notes = ["C", "D", "E", "F", "G", "A"] >>> musical_notes.append("B")
  • First, the list is defined and assigned to a variable.
  • Then, using this variable we call the append() method, passing the element that we want to append (the string «B» ) as argument.

🔹 Effect & Return Value

This method mutates (changes) the original list in memory. It doesn’t return a new copy of the list as we might intuitively think, it returns None . Therefore, just by calling this method you are modifying the original list.

>>> musical_notes = ["C", "D", "E", "F", "G", "A"] >>> musical_notes.append("B")

You can see (below) that the original list was modified after appending the element. The last element is now «B» and the original list is now the modified version.

>>> musical_notes ['C', 'D', 'E', 'F', 'G', 'A', 'B']

You can confirm that the return value of append() is None by assigning this value to a variable and printing it:

>>> musical_notes = ["C", "D", "E", "F", "G", "A"] >>> a = musical_notes.append("B") >>> print(a) None

🔸 Examples

Now that you know the purpose, syntax, and effect of the append() method, let’s see some examples of its use with various data types.

Append a String

>>> top_players = ["gino234", "nor233", "lal453"] >>> top_players.append("auop342") # The string was appended >>> top_players ['gino234', 'nor233', 'lal453', 'auop342']

Append an Integer

>>> data = [435, 324, 275, 567, 123] >>> data.append(456) >>> data [435, 324, 275, 567, 123, 456]

Append a Float

>>> data = [435.34, 324.35, 275.45, 567.34, 123.23] >>> data.append(456.23) >>> data [435.34, 324.35, 275.45, 567.34, 123.23, 456.23]

Append a Boolean Value

>>> values = [True, True, False, True] >>> values.append(False) >>> values [True, True, False, True, False]

Append a List

This method appends a single element to the end of the list, so if you pass a list as argument, the entire list will be appended as a single element (it will be a nested list within the original list).

>>> data = [[4.5, 4.8, 5.7], [2.5, 2.6, 2.7]] >>> data.append([6.7, 2.3]) >>> data [[4.5, 4.8, 5.7], [2.5, 2.6, 2.7], [6.7, 2.3]]

Append a Tuple

This works exactly the same for tuples, the entire tuple is appended as a single element.

>>> data = [[4.5, 4.8, 5.7], [2.5, 2.6, 2.7]] >>> data.append((6.7, 2.3)) >>> data [[4.5, 4.8, 5.7], [2.5, 2.6, 2.7], (6.7, 2.3)] 

💡 Tip: If you need to add the elements of a list or tuple as individual elements of the original list, you need to use the extend() method instead of append() . To learn more about this, you can read my article: Python List Append VS Python List Extend – The Difference Explained with Array Method Examples

Append a dictionary

Similarly, if you try to append a dictionary, the entire dictionary will be appended as a single element of the list.

🔹 Equivalence of Append and Insert

An interesting tip is that the insert() method can be equivalent to append() if we pass the correct arguments.

The insert() method is used to insert an element at a particular index (position) in the list.

This is the syntax used to call the insert() method:

image-61

To make it equivalent to append() :

  • The value of index has to be the length of the list ( len() ) because we want the element to be the last element of the list.

Here’s an example that shows that the result of using insert with these arguments is equivalent to append() :

>>> musical_notes = ["C", "D", "E", "F", "G", "A"] >>> musical_notes.insert(len(musical_notes), "B") >>> musical_notes ['C', 'D', 'E', 'F', 'G', 'A', 'B']

But as you have seen, append() is much more concise and practical, so it’s usually recommended to use it in this case.

🔸 Equivalence of Append and List Slicing

There is also an interesting equivalence between the append() method and list slicing.

image-62

This syntax is essentially assigning the list that contains the element [] as the last portion (end) of the list. Here you can see that the result is equivalent to append() :

>>> musical_notes = ["C", "D", "E", "F", "G", "A"] >>> musical_notes[len(musical_notes):] = ["B"] >>> musical_notes ['C', 'D', 'E', 'F', 'G', 'A', 'B']

These are interesting alternatives, but for practical purposes we typically use append() because it’s a priceless tool that Python offers. It is precise, concise, and easy to use.

I really hope that you liked my article and found it helpful. Now you can work with append() in your Python projects. Check out my online courses. Follow me on Twitter. ⭐️

Источник

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