Home > Software design >  How can I add two elements in a list in this manner?
How can I add two elements in a list in this manner?

Time:01-02

So I'm trying to find how can I append two items into my new list r under the function histogram. I've learnt that using extend, I am able to use commas to add more than one element each time. However, when I tried to do this, I get an error message saying

TypeError: list.extend() takes exactly one argument (2 given)

What am I doing wrong here?? Am I misunderstanding the syntax of the list.extend function?

Here is my code btw..

def reverse(filename):
    s = open(filename, 'r')
    content = s.read()
    return list(content)
print(reverse('data'))

def histogram(filename):
    g: list = reverse(filename)
    r = []
    for x in g:
        r.extend(x, g.count(x))
    return r

print(histogram('data'))

CodePudding user response:

As the error message mentions, extend receives one argument only, a list, and concatenate it to the list that calls the function. If you want to add a single element to a list, use append. For example:

a = [1, 2]
b = [3, 4]

b.extend(a)
print(b) # [3, 4, 1, 2]

b.append(5)
print(b) # [3, 4, 1, 2, 5]

In order to add 2 elements into your list, you can do:

r.extend([x, g.count(x)])

CodePudding user response:

In addition to answer given by @Gabip,

"I've learnt that using extend, I am able to use commas to add more than one element each time", you can consider it as the incomplete information of the extend function.

To further clarify between extend and append. append adds the argument as a single value at the end of the list and extend iterates over its argument and add it at the end of the list.

x = [1, 2, 3]

"""list.append"""
x.append(2)
>>> [1, 2, 3, 2]

x.append([2, 3])
>>> [1, 2, 3, [2, 3]]

"""list.extend"""
x.extend(2)
>>> TypeError: 'int' object is not iterable

x.extend([2])
>>> [1, 2, 3, 2]

x.extend([ [2] ])
>>> [1, 2, 3, [2]]
  • Related