1

Apparently, I have a problem with my code. I run the below module with Python 3.6.6 Shell. I want to check whether elements of size 4 exists on list a_list and copy them to b_list. There is only one such element ('3m7n'), but it is decomposed in 4 others ('3', 'm', '7', 'n'). Why?

a_list = ['2', '3m7n', '3', '17', None]  
b_list = ['bat', 'zoo', 'next', 'pina', 'pinta']  
for i in a_list:  
    if i==None:
        pass  
    elif len(i)==4:  
        b_list.extend(i)  
b_list  
['bat', 'zoo', 'next', 'pina', 'pinta', '3', 'm', '7', 'n']

enter image description here

Ramon
  • 518
  • 6
  • 16
  • Can you please paste the code as text in your question? It is hard people to help with an image of your code. – slider Nov 26 '18 at 04:00
  • Use `append` instead of `extend`. https://stackoverflow.com/questions/252703/difference-between-append-vs-extend-list-methods-in-python – slider Nov 26 '18 at 04:04

2 Answers2

2

extend expects a list append expects an element

a_list = ['2', '3m7n', '3', '17']
b_list = ['bat', 'zoo', 'next']

b_list.extend([i for i in a_list if len(i) == 4 ])
print(b_list)
Krishna
  • 924
  • 1
  • 7
  • 28
0

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.

BernardL
  • 5,162
  • 7
  • 28
  • 47