Inserting a string into a list of ints

Asked

Viewed 86 times

1

I have the following rule:

Create a function that receives a list of integers, and replaces the items as below:

  • if Multiples of 3 = 'Fizz'
  • multiples of 5 = 'Buzz'
  • multiples of 3 and 5 = 'Fizzbuzz'

I created the program below:

    intList = list()
intList = [1,2,3,4,5,6,7,8,9,10,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28]
newlist=list()

def fizzbuzz( lista ):
   for item in lista:
       if item % 3 == 0 and item % 5 == 0:
           lista.remove(item)
           newlist.append(item) ='fizzbuzz'
       elif  item % 3 == 0:
           lista.remove(item)
           newlist.append(item) ='fizz'
       elif  item % 5 == 0:
           lista.remove(item)
           newlist.append(item)='buzz'
       else:
           newlist.append(item)=item


fizzbuzz(newlist)

But returns the following error:

C: Python27 my_scripts>for_loop.py File "C: Python27 my_scripts for_loop.py", line 15 newlist.append(item)='buzz' Syntaxerror: can’t assign to Function call

Any idea what I can do? At the end of the precise program displays the list of integers and strings.

Thanks!

2 answers

0

I have no experience in Python, but I believe the four "append" calls are wrong. Try to change

newlist.append(item) ='fizzbuzz'

for

newlist.append('fizzbuzz')
  • Thank you so much TNT! It worked, thanks!

  • Plz, if possible mark as answered and give a note up. Thank you!

  • I tried TNT, but only one answer can be marked as correct, note up tb is not available to me pq it is necessary level 15 of reputation to be able to mark it.

0


Syntaxerror: can’t assign to Function call

This error is happening because you are trying to assign a value in a function call.

Ex:

newlist.append(item) ='fizzbuzz'

You are trying to assign a value in the function append.

As mentioned by @TNT, you have to change your syntax.

intList = list()
intList = [1,2,3,4,5,6,7,8,9,10,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28]
newlist=list()

def fizzbuzz( lista ):
   for item in lista:
       if item % 3 == 0 and item % 5 == 0:
           lista.remove(item)
           newlist.append('fizzbuzz')
       elif  item % 3 == 0:
           lista.remove(item)
           newlist.append('fizz')
       elif  item % 5 == 0:
           lista.remove(item)
           newlist.append('buzz')
       else:
           newlist.append(item)

fizzbuzz(intList)

print(newlist)

Functional Example
https://repl.it/DyIS/1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.