Home > Software engineering >  How can I append multiple string variables into a single list, and have then separate?
How can I append multiple string variables into a single list, and have then separate?

Time:09-27

If I have a list, and I have two string variables which both contain unique information. I would like them both to be appended into a list, and be separate values so that the length of the list is two

list = []

base3 = 'h'

base2 = 'w'

ttl = base3, base2
list.append(ttl)
print(list)
print(len(list))

adding the two strings together

ttl = base3 base2

makes the list have a length of 1. I want the list to have a length of 2 if two variables are added, 3 if three variables are added, and so on.

CodePudding user response:

The smallest change you can make is to use extend rather than append:

list = []

base3 = 'h'

base2 = 'w'

ttl = base3 , base2
list.extend(ttl)
print(list)
print(len(list))

Result:

['h', 'w']
2

Your code creates in ttl a tuple containing the two strings 'h' and 'w'. A tuple is like a list but can't be modified once it is created. It is an iterable, meaning that it contains multiple items that can be acted on one by one.

list.append(argument) always adds a single item to a list, where that item is whatever argument you pass to the list. So in your original code, you were adding a single item to the list, the tuple you created and stored in ttl.

list.extend(argument) accepts a list, a tuple, or some other iterable, and it adds each of the items IN the argument passed to it. This is the behavior you wanted. In your case, this adds each of the strings in your ttl tuple to the list.

CodePudding user response:

The simplest way to turn a tuple into a list is with the list function:

>>> base3 = 'h'
>>> base2 = 'w'
>>> ttl = base3, base2
>>> list(ttl)
['h', 'w']

Note that this does not work if you already overwrote the name list with your own variable by doing something like:

list = []  # never do this!

CodePudding user response:

If you want [base2, base3], just do it :)

my_list = [base2, base3]
  • Related