Contents:

Master Python with a free course and create a Telegram bot, web parser, and website from scratch under the guidance of an expert from Sber.
Learn moreThe append() and extend() methods allow you to add new elements to an existing list, as well as combine several lists into one. In this article, we will consider their use with examples. In conclusion, we will share some lesser-known methods that will also help in expanding lists.
The append() function in Python: how does it work?
The append() method adds the specified element to the end of the list. Like all other methods in Python, it must be called with the dot operator.
The append() method takes a single argument, item, which is added to the end of the list. The argument can be of any type: numbers, strings, dictionaries, and other objects. The method returns None, which means that it returns nothing.
Suppose we have a list a containing strings.
To include a new row, ‘row’, in it, we must pass it as an argument to the append() method. Since this method is of type list, it should be called on the a object, using the dot operator:
The new string has been successfully added to the end of our list. Everything works as expected.
Let's complicate the problem by adding another list consisting of two strings:
We observe that the list b, which includes the nested elements, has been appended to the elements of a. However, what if we want the elements of b to be added individually? For example, like this:
Unfortunately, the append() method does not allow this operation, since it takes only one argument. If you try to pass multiple objects separated by commas, the interpreter will throw a TypeError exception.
Luckily, there's an extend() method that allows you to append multiple elements at once. We'll discuss this in the next section.
The extend() Function in Python: How Does It Work?
The extend() method takes an iterable as an argument and appends its elements to an existing list.
The extend() function adds additional elements to the end of a list, but unlike the append() method, it can accept iterables such as lists, tuples, and strings as arguments. In this case, the lists being concatenated can include elements of different types, which allows, for example, combining strings with numbers, or numbers with tuples.
Similar to the append() method, this method also returns None.
Let's go back to our list a:
Suppose we need to concatenate it with another list containing strings. We can pass the variable b to the extend() method, which will allow us to get the desired result:
As you can see, each component of b was individually included in a.
Similarly, we can apply similar operations to other iterables, such as tuples or strings.
Keep in mind that when using the extend() method, strings are converted to character lists, and elements are added one at a time. For example, the string ‘man’ will be split into individual characters: ‘m’, ‘a’, and ‘n’.
When a non-iterable object, such as a number, is passed to extend(), Python throws a TypeError.
The error message correctly explains that a number is not an iterable.
Alternative Methods for Appending Items to a List
To make life easier for Python programmers, the language's creators have implemented several functions that allow you to quickly append items to lists.
The + operator may resemble a familiar mathematical sign, but when it comes to lists, it functions similarly to the extend() method:
All the elements from the first list have been added to the end of the second.
Slicing. An alternative method for adding elements to a list is an unusual use of indexing. It looks like this:
This may seem a bit unusual, but it's actually effective. When we try to access elements of a that aren't present, the language automatically adds elements from the list b we referenced on the right side of the assignment operator.
What to Remember
- The append() method allows you to add a single item to a list, whether it's a number, a string, or even another list.
- The extend() method works similarly to append(), but its argument can be any iterable, such as a list, tuple, or string. The elements of this object are added to another list one at a time.
- In addition to using the append() and extend() methods, you can add elements to a list using the + operator and slicing. Both of these approaches work similarly to extend(), adding elements from one list to another one at a time.
We have a lot of exciting coding content waiting for you in our Telegram channel. Don't miss the opportunity to subscribe!
Read also:
- Learn Python on your own for free: a step-by-step plan
1. Define Your Goals. Before diving into learning, think about what problem you want to solve with Python. This could be web development, data analysis, task automation, or game development. Having a clear understanding of your goals will help you focus on the right materials.
2. Find Quality Resources. There are many free courses, video tutorials, and textbooks available online. Explore platforms like Coursera, edX, Codecademy, and YouTube to find the right courses.
3. Start with the Basics. Master the basic concepts of the language, such as syntax, variables, data types, operators, and control structures. This is the foundation on which further learning is built.
4. Practice. Regular practice is the key to successful language mastery. Use online platforms like LeetCode or HackerRank to solve problems and participate in programming competitions.
5. Develop Your Projects. Apply what you've learned in practice by creating your own projects. These can be simple scripts, applications, or even games. Project activities help deepen your knowledge and understand how to apply the language in real-world settings.
6. Explore libraries and frameworks. Once you've mastered the basics, get familiar with popular libraries such as NumPy, Pandas, and Matplotlib for data analysis, or Flask and Django for web development. They will expand your capabilities and help deepen your knowledge.
7. Participate in communities. Join forums, social media groups, and chat rooms dedicated to Python. Communicating with like-minded and experienced programmers will help you gain new knowledge, advice, and support.
8. Don't be afraid of mistakes. Mistakes are a natural part of the learning process. Don't hesitate to ask questions and look for solutions when you encounter difficulties. This will help you become more confident in your skills.
9. Constantly develop. Programming is a field that is constantly changing. Follow new trends, read articles, books, and blogs to stay up to date with current technologies and approaches.
Following this algorithm, you can effectively learn Python on your own and without financial costs.
- “Changed my career before the moment of regret came”: Why a cyber policeman decided to move to the field of information technology.
- Recursion is a programming technique in which a function calls itself to solve a problem. This approach is often used to solve problems that can be broken down into smaller, similar subproblems. Let's consider how recursion works using the Python language as an example.
Suppose we need to calculate the factorial of a number. The factorial n (denoted as n!) is the product of all positive integers from 1 to n. For example, the factorial of 5 is 5 × 4 × 3 × 2 × 1, which is 120.
We can define a recursive function to calculate the factorial as follows:
1. Define the base case that will terminate the recursive calls. Typically, this is the condition under which the function stops calling itself. In the case of the factorial, the base case will be 0! = 1.
2. Define the recursive case in which the function calls itself with an argument that decreases by one. This will be n! = n × (n — 1)!.
Now let's look at the implementation of this idea in Python:
«`python
def factorial(n):
if n == 0: # base case
return 1
else: # recursive case
return n * factorial(n — 1)
«`When we call `factorial(5)`, the process will look like this:
— `factorial(5)` calls `factorial(4)`
— `factorial(4)` calls `factorial(3)`
— `factorial(3)` calls `factorial(2)`
— `factorial(2)` calls `factorial(1)`
— `factorial(1)` calls `factorial(0)`At this point, since n is 0, the base case is triggered and the function returns 1. Then the results start to trickle back through all the previous calls:
— `factorial(1)` returns 1 × 1 = 1
— `factorial(2)` returns 2 × 1 = 2
— `factorial(3)` returns 3 × 2 = 6
— `factorial(4)` returns 4 × 6 = 24
— `factorial(5)` returns 5 × 24 = 120.So, the final result of calling `factorial(5)` is 120. Recursion allows for compact and convenient problem solving, but it is important to be aware of possible limitations, such as the depth of recursion, which can lead to stack overflow errors if the number of recursive calls is too large.
