Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : append a list to a list

I'm doing some exercises in Python and I came across a doubt. I have to set a list containing the first three elements of list, with the .append method. The thing is, I get an assertion error, lists don't match. If I print list_first_3 I get "[['cat', 3.14, 'dog']]", so the double square brackets are the problem. But how can I define the list so the output matches?

list = ["cat", 3.14, "dog", 81, 6, 41]
list_first_3 = []
list_first_3.append(list[:3])

    
assert list_first_3 == ["cat", 3.14, "dog"]
like image 824
santoros Avatar asked Aug 31 '26 02:08

santoros


2 Answers

append can only add a single value. I think what you may be thinking of is the extend method (or the += operator)

list1 = ["cat", 3.14, "dog", 81, 6, 41]
list_first_3 = []
list_first_3.extend(list1[:3])

assert list_first_3 == ["cat", 3.14, "dog"]

or

list1 = ["cat", 3.14, "dog", 81, 6, 41]
list_first_3 = []
list_first_3 += list1[:3]

assert list_first_3 == ["cat", 3.14, "dog"]

otherwise you'll need a loop:

list1 = ["cat", 3.14, "dog", 81, 6, 41]
list_first_3 = []
for value in list1[:3]: list_first_3.append(value) 

assert list_first_3 == ["cat", 3.14, "dog"]

with append but without a loop would be possible using a little map() trickery:

list1 = ["cat", 3.14, "dog", 81, 6, 41]
list_first_3 = []
any(map(list_first_3.append,list1[:3]))

assert list_first_3 == ["cat", 3.14, "dog"]
like image 76
Alain T. Avatar answered Sep 02 '26 17:09

Alain T.


When appending a list to a list, the list becomes a new item of the original list:

list_first_3 == [["cat", 3.14, "dog"]]

You are looking for:

list_first_3 += list[:3] # ["cat", 3.14, "dog"]

This adds every item from list to list_first_3.

Also you shouldn't name your variables like inbuilt types like list.

If you NEED to append, you could use a for-loop:

list_first_three = []
for item in list[:3]:
    list_first_three.append(item)
like image 31
Honn Avatar answered Sep 02 '26 17:09

Honn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!