1/13/2024 0 Comments List extend pythonThis behavior is obviously different from that of the append method. Three integer objects were appended to the list and the list size grew by three. > L = Īs you can see in the example above, extend takes a list (which is an iterable) as an argument and appends each item of the list to L. What extend does is very straightforward, it iterates through the iterable object one item at a time and appends each item to the list.įor example, let’s try to extend a list by another list. Unlike append that can take an object of any type as an argument, extend can only take an iterable object as an argument.Īn iterable object is an object that you can iterate through like strings, lists, tuples, dicts, or any object with the _iter_() method. Second: ExtendĮxtend is another very common list method. Now let’s take a look at a similar, yet different, method. So what we did here is we appended one object (which happens to be of type list) to our list LĪgain, after the modification the list length grew by only one. This is an important distinction because you will see later that this is not necessarily the case with extend.Īlright, just out of curiosity let’s try to append a list to our list. Needless to say, the length of the list has increased by one (and only one) because the append method adds only one object to the list. Say you want to append an item to a list L>/span> that initially has 4 elements > L = Īs you can see, the append method adds the new item 5 to the list. This object can be of any data type, a string, an integer, a boolean, or even another list. The append method is used to add an object to a list. In this article, I will explain what each method does and show you exactly the difference between them. However, these two methods are the cause of a lot of confusion and misunderstanding among Python beginners. ![]() ![]() Two of the most common List methods in Python are the append and extend methods.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |