append multiple elements 1

append multiple elements

>>> lst = [1, 2]
>>> lst.append(3)
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]

>>> lst.extend([5, 6, 7])
>>> lst.extend((8, 9, 10))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> lst.extend(range(11, 14))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

Here is what the above code is Doing:
1. Creating a list with the elements 1 and 2.
2. Appending the element 3 to the list.
3. Appending the element 4 to the list.
4. Extending the list with the elements 5, 6, and 7.
5. Extending the list with the elements 8, 9, and 10.
6. Extending the list with the elements 11, 12, and 13.

The extend() method is very similar to the append() method, but there is one key difference between them.

The append() method adds a single element to the end of a list, while the extend() method adds the elements of an iterable (such as a list) to the end of the list.

The extend() method is commonly used to add the elements of a list (or any iterable) to another list.

For example, you could use the extend() method to add the elements of a list to the end of another list:

>>> lst1 = [1, 2, 3]
>>> lst2 = [4, 5, 6]
>>> lst1.extend(lst2)
>>> lst1
[1, 2, 3, 4, 5, 6]

>>> lst2
[4, 5, 6]

The extend() method doesn’t return any value, but it does modify the list it’s called on.

If you want to add the elements of a list to another list and get a new list as a result, you can use the + operator:

>>> lst1 = [1, 2, 3]
>>> lst2 = [4, 5, 6]
>>> lst3 = lst1 + lst2
>>> lst3
[1, 2, 3, 4, 5, 6]

>>> lst1
[1, 2, 3]

>>> lst2
[4, 5, 6]

The + operator creates a new list and adds the elements of the two lists to it.

The extend() method modifies the list it’s called on, while the + operator creates a new list.

The extend() method is faster than the + operator because it doesn’t have to create a new list and copy the elements to it.

The extend() method is commonly used to

Similar Posts