How does the *= operator work?

Question

How does the *= operator work?

Answer

The *= operator takes the value currently stored in the variable on the left and multiplies it by the value on the right, then stores the result back into that variable. It saves us from having to rewrite the name of the variable on the right side of the =, like this:

my_var = 10
my_var *= 10  # 100

longer = 10
longer = longer * 10  # 100
2 Likes

my_var *= 10 is essentially the same as my_var = my_var * 10

my_var = 10
my_var =  my_var * 10 
or 
my_var  *= 10

it multiplys my_var with number 10 in bouth way

A question, take a look on this:

def product(list):
  total = 1  # if 0 then 0, if 2 then 200, and so on...ok
  for num in list: # this is a loop...ok
    total = total * num  # and here...where is this "[4*5*5]", in which part?
  return total 

print product([4, 5, 5])

Ok, I dont get it, how this function knew to multiple like that? Anyone understand my question?

I also don’t understand this. Can someone please explain?

You set your total = 1. While iterating through list (which is e.g. 4,5,5): first iteration: total = 14 , next iteration: total = (14)5, last iteration total = (14*5)*5.

if you print out whats happening, you can sort of see how it works…

  def product(list):
	total = 1
	for num in list:
		print(str(total)+'*'+str(num))
		total = total*num
	return total

print(product([4,5,5]))
1 Like

Why can we do this function without using split to take out the values, like in censor?

Censor:
def censor(text, word):
words = text.split()
result = ‘’
stars = ‘*’ * len(word)
count = 0
for i in words:
if i == word:
words[count] = stars
count += 1
result =’ '.join(words)

And the current one:
def product (integers):
total = 1
for numbers in integers:
total *= numbers
return total

print product([4, 5, 5])

text is a single string, consisting of words separated by spaces. The expression words = text.split() returns a list consisting of the individual words from the string text. The remainder of the function operates on that list, words.

In your second example, the parameter integers is already a list.

why is this whole lesson with 15 HARD AF

7 Likes

This link might help
http://www.pythontutor.com/visualize.html#mode=display

1 Like

It helps to add in a bunch of print statements like so:

def product(items_to_multiply):
  total = 1
  print "Loops are about to start, with each loop grabbing only a single list item in items_to_multiply..."
  for num in items_to_multiply:
    print "Start of a loop. Here is the list item for this loop: " + str(num)
    print "This is the total BEFORE we multiply that list item: " + str(total)
    total = total * num
    print "This is the NEW total: " + str(total)
  return total 

product([4, 5, 5])

image

(edit: grammar)
The product script we needed to write felt very similar to the count script from the previous lesson.
E.G. the former script ran through a list(s) and counted the times a given argument was contained in the list(s).
I felt this script would be very similar in nature and my code works with only one list.
However, when given a list that contains more lists (similar to the pervious lesson) it fails to iterate through the second list on “product.”
I am not sure why the same code has two behaviors, what am I missing?

product code:

def product(sequence):
  result = 1
  for x in sequence:
    print sequence
    print
    for y in x:
      int(y)
      print y
      result *= y
    print
    print type(y)
    return result

print product([[4, 5, 5], [1,3]])

counter code:

def count(sequence,item):
  print "Sequence(s) to check: ", sequence
  print "Check for #: ", item
  print
  accumulator = 0
  for x in sequence:
    for y in x:
      print y
      if y == item:
        accumulator += 1
  print
  print "your number:",item, "was counted this many times:"
  return accumulator

print count([[11, 1, 1, 2, 2222], [1, 4], [1, 4]], 1)

For that print statement one expects it would be print x, so it will echo, [4, 5, 5] and [1, 3], successively.

int(y)

that line is not a statement so does nothing. It’s moot that y is already an integer. If it were not, what would we prove by casting it to one? It will affect the end product.

There is the problem. return is inside the outer loop so never gets to the second sequence.

>>> def product(sequence):
  result = 1
  for x in sequence:
    print (x)
    for y in x:
      print (y)
      result *= y
  return result

>>> product([[4, 5, 5], [1,3]])
[4, 5, 5]
4
5
5
[1, 3]
1
3
300
>>> 

Aside

The above function is trapped in a bubble in terms of re-usability since it is confined (fixed) to a list of lists. What happens if we pass in a single list with no nested members?

>>> product([4, 5, 5, 1, 3])
4
Traceback (most recent call last):
  File "<pyshell#82>", line 1, in <module>
    product([4, 5, 5, 1, 3])
  File "<pyshell#77>", line 5, in product
    for y in x:
TypeError: 'int' object is not iterable
>>> 

Or a list with nested lists that are also nested lists?

>>> product([[4, [5, 5]], [1, [3]]])
[4, [5, 5]]
4
[5, 5]
[1, [3]]
1
[3]
Traceback (most recent call last):
  File "<pyshell#83>", line 1, in <module>
    product([[4, [5, 5]], [1,[3]]])
  File "<pyshell#77>", line 7, in product
    result *= y
TypeError: can't multiply sequence by non-int of type 'list'
>>> 

The parameter name is somewhat misleading since we first think of a sequence as being a flat list. A minor point, though.

How can we make this function more flexible and re-usable in all sorts of situations? Since we want the product of all the numbers in the list(s) then it makes sense to consider flattening the list.

That may be a new concept, as well as the consideration of how expensive nested lists are in terms of time complexity (Big-O, for later study). List flattening is the process of breaking all the values out of their respective lists into a single, flat list.

>>> def flatten(s):
    if type(s) != list: raise TypeError
    if s == []: return s
    if type(s[0]) == list:
        return flatten(s[0]) + flatten(s[1:])
    return s[:1] + flatten(s[1:])

>>> flatten([[4, [5, 5]], [1,[3]]])
[4, 5, 5, 1, 3]
>>> flatten([[4, [5, 5], 4, [5, [4, 5]], [1, [3], [1, [1, [1, 3]]]]]])
[4, 5, 5, 4, 5, 4, 5, 1, 3, 1, 1, 1, 3]
>>> 

No, this is not something you are expected to know or even understand. It’s a function that uses recursion to drill down into all the nested layers, gradually reducing the input to a flattened list. List slicing and recursion will come up in your learning but I don’t believe it is covered in the Python 2 track (I’ve been wrong, before).

Add all this to your extra study list and take it up when you’ve got far enough along.


So now that we have a function to flatten lists,

>>> def product(data):
    sequence = flatten(data)    #  dependency
    result = 1
    for x in sequence:
        result *= x
    return result

>>> product([[4, [5, 5], 4, [5, [4, 5]], [1,[3], [1, [1, [1, 3]]]]]])
360000
>>> 
1 Like

Good day! May I ask for a help to look at the code I provided below? I want to call the desired summary of integer with an empty list, but I am not understanding the output of my code. It gives me 105 instead 100.

Thanks in advance!

There is some weird stuff going on with the list in the prod() not sure what the end goal is there. What is the purpose of the list?

I just want to multiply the sum of product with an empty list without using a number part. an integer.

>>> lst = [1, 2]
>>> lst *= 3
>>> lst
[1, 2, 1, 2, 1, 2]
>>> 

Note the behavior above when we multiply a list by a number. In this instance *= is a repeat operator.

Yes, I am agree with you. For a challange I want to figure out if it is possible to get the desired output of the assigment with an empty list. My second code above gives the output 105 and I could not understand how the 5 was added to 100.

Your code is effectively doing the following…

>>> lst = [4]
>>> lst *= 4
>>> lst.append(5)
>>> lst *= 5
>>> lst
[4, 4, 4, 4, 5, 4, 4, 4, 4, 5, 4, 4, 4, 4, 5, 4, 4, 4, 4, 5, 4, 4, 4, 4, 5]
>>> sum(lst)
105
>>> 

Still not clear what the objective is. Do you want a product, or a sum?

4 * 5 * 5 == 100

4 + 5 + 5 == 14

Now, I understand how the output 105 is counted in the code.

I have already got the output of product. It is to see in the screenshot. Thanks @mtf for elucidating.

1 Like