Using .append on multiple string elements at a time

This is probably the main question for most of you, but I can't seem to find any specific information on googling or on any of the previously asked questions:

I would like to know if it is possible to add multiple items to a list already containing one item using .append and then get the output number of all of them using len()

. When I enter my code like this:

bag.append('suit', 'shoes', 'socks')

      

I am getting the following error:

TypeError: append() takes exactly one argument (3 given)

      

I've tried double parentheses like this:

bag.append(('suit', 'shoes', 'socks))

      

but this ends up len(bag)

telling me that bag

there are only 2 elements in (i.e. the original and (suit, shoes, socks)

). The number for which 4 is calculated (for example, original item + suit + shoes + socks).

The only method I've used that successfully accomplished this is as follows:

bag.append('suit')
bag.append('shoes')
bag.append('socks')

      

When running len(bag)

on this, I get the correct output for 4 items separately, i.e. 4 (original item bag = [gloves] + "suit" + "shoes" + 'socks .

+3


source to share


3 answers


You can add two lists together using the operator +



>>> l = ['hat', 'coat']
>>> x = l + ['suit', 'shoes', 'socks']
>>> x
['hat', 'coat', 'suit', 'shoes', 'socks']

      

+1


source


Instead append

, extend

:

bag.extend(['suit', 'shoes', 'socks'])

      



See here .

+5


source


As the saying goes TypeError

, append input is only one element, so any attempt to add more than one element on the same call will fail.

Reason bag.append(('suit', 'shoes', 'socks))

didn’t work, as ('suit', 'shoes', 'socks)

is one type of element tuple .

Use a method extend

or operator +

as suggested here.

+2


source







All Articles