JuniorCodeOccasionalNot answered yet
What does [1, 2, 3].extend('abc') produce, and why?
Predict the output and explain how extend treats its argument.
l = [1, 2, 3]
l.extend('abc')
print(l)
Determine the output.
Prints [1, 2, 3, 'a', 'b', 'c']. extend iterates its argument and appends each item; a string is iterable over its characters, so each char is added separately. To add the whole string as one element use l.append('abc'), which gives [1, 2, 3, 'abc'].
- ✗Expecting
extendto add the string as one element likeappend - ✗Thinking
extendrejects anything that is not a list - ✗Forgetting a string is iterable over its characters
- →How would you append the whole string as a single element instead?
- →What does
[1, 2].extend(3)raise, and why?