An iterable value is a value that represents a sequence of one more values. In order to see if a value is iterable, check if it has the .__iter__
method.
list = [1,2,3,4,6]# Check whether it's iterableprint (list.__iter__)
There are two methods available, extend()
and append()
. These are both built-in Python functions and are used to extend a list. However, the way they add elements to the list is very different:
extend()
The extend()
function takes an iterable value and adds each element of it to the list one at a time. This method concatenates the first list with another list (or another iterable). The length of the list will increase by the same number of elements that were in the iterable argument.
x = [1, 2, 3]x.extend([4, 5])print (x)
append()
The append()
function adds its argument to the end of the list as a single item. It treats the entire piece as a single argument. This method simply adds elements to a list.
When the append()
function is called,the length of the list itself will only increase by one.
x = [1, 2, 3]x.append([4, 5])print (x)