conyieie
conyieie

Reputation: 225

How do I control the amount of times something is added to a list?

I have a list, and I am trying to add a certain amount of variables to it:

newList = ["Andrew", "Ben", "Happy"]
SecondList = [2,3,1]
BestList = []
for g in range(0,3):
    BestList.append((newList[g])*(int(SecondList[g])))
print (len(BestList))
print (BestList)

The problem is I want the "Andrew" variable to be appended to the list 2 times, but instead, it is appended to the list only once, but as "AndrewAndrew". How do I fix my code in a way where instead of multiplying "Andrew" twice and adding it to the list as that one variable, it is added to the list twice. My end goal is for the length of BestList to be 6.

Thanks in advance.

Upvotes: 0

Views: 40

Answers (3)

Sowjanya R Bhat
Sowjanya R Bhat

Reputation: 1168

You missed to use the proper loops.

Code:

names_list = ["Andrew", "Ben", "Happy"]
counts_list = [2,3,1]
final_list = []

for i in range(len(names_list)):
  [final_list.append(names_list[i]) for j in range(counts_list[i])]

print(final_list)

Output:

["Andrew", "Andrew", "Ben", "Ben", "Ben", "Happy"]

Upvotes: 0

MalteHerrmann
MalteHerrmann

Reputation: 328

The problem is that you are multiplying the string with the integer value. As in mathematics, this is interpreted as "Andrew" * 2 = "Andrew" + "Andrew", which is equal to "AndrewAndrew".

To get the behaviour you're looking for you can introduce another for loop. Also, beware that for i in range(...) and using indexing for list list[i] is considered unpythonic. A better way would be to directly iterate over the list entries.

newList = ["Andrew", "Ben", "Happy"]
SecondList = [2,3,1]
BestList = []
for name, amount in zip(newList, SecondList):
    for _ in range(amount):
        BestList.append(name)

print (len(BestList))
print (BestList)

Upvotes: 2

rdas
rdas

Reputation: 21285

Couple of things:

  1. If you multiply a string using * with an integer, you get a string (which is the original string repeated that many times)

  2. If you use append only one new element is added to the list. If you want to add multiple, you need to use extend

newList = ["Andrew", "Ben", "Happy"]
SecondList = [2,3,1]
BestList = []
for g in range(0,3):
    BestList.extend([newList[g]]*SecondList[g])
print (len(BestList))
print (BestList)

Note how I've used [newList[g]] - this turns the string from newList into a single element list. Now if you multiply this list with an int, you get another list which is the same element repeated that many times.

Result:

6
['Andrew', 'Andrew', 'Ben', 'Ben', 'Ben', 'Happy']

If you indeed wanted something like:

[['Andrew', 'Andrew'], ['Ben', 'Ben', 'Ben'], ['Happy']]

Simply ignore the second point and keep using append instead

Upvotes: 2

Related Questions