append
adds an object to the end of the list, as a list is a mutable data type, you can append to the end of a list. extend
adds each element in an iterable to the end of the list.
The mistake you are making is extending a list with a str
sequence, if you want to add an object use append:
a = ['2', '3m7n', '3', '17']
b = ['bat', 'zoo', 'next']
for i in a:
if len(i) == 4:
b.append(i)
b
['bat', 'zoo', 'next', '3', 'm', '7', 'n']
The error you made using extend is where you extended the list with a string, which then treats it as an iterable and goes through each character of the string, similar to something like for i in '3m7n': print(i)
. Using the same context, but converting each item in the loop to a list
, you use extend to add each item in the list:
a = ['2', '3m7n', '3', '17']
b = ['bat', 'zoo', 'next']
for i in a:
if len(i) == 4:
b.extend([i])
b
>>['bat', 'zoo', 'next', '3m7n']
For the sake of simplicity, readability and a little more efficiency, you can use a list comprehension to replace the for
loop:
b.extend([i for i in a if len(i) == 4 ])
And if you observe, it works exactly the same as the for loop, by extending the list with a list object.