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? Thanks
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"]
CodePudding user response:
Your problem is that you try to append a list to another list.
list[:3]
will return you the result ["cat", 3.14, "dog"]
Then, you take that result as a whole and put it as an item in list_first_3
.
If you want to fix that, you can do:
list = ["cat", 3.14, "dog", 81, 6, 41]
list_first_3 = []
list_first_3 = list[:3]
assert list_first_3 == ["cat", 3.14, "dog"] # Return True
And if you insist using append
method:
list = ["cat", 3.14, "dog", 81, 6, 41]
list_first_3 = []
for item in list[:3]
list_first_3.append(item)
assert list_first_3 == ["cat", 3.14, "dog"] # Return True
CodePudding user response:
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)
CodePudding user response:
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"]