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
3 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?

1 Like

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

1 Like

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.

1 Like

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]))
2 Likes

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

4 Likes

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

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