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"]
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"]
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With