89DEVs

How to multiply in Python?

How to multiply in Python?

To multiply in Python, use the asterisk character (*) to multiply two or more values.

multiply integers

If both numbers are integers, Python will return the product as int. # multiply integers my_product = 2 * 2 print(my_product) The product of 2 * 2 is 4. The result is returned as integer value and printed. 4

multiply floats

If one of the values is a float value, the product will be a float value as well. # multiply float values my_product = 2.5 * 2 print(my_product) The product of 2.5 * 2 is 5.0. The result is returned as float value and printed. 5.0

multiply complex numbers

A complex number contains a real and imaginary part. To multiply complex numbers in Python, use the * operator. # multiply complex number myComplexNumber1 = complex(2, 3) myComplexNumber2 = complex(4, 5) myProduct = myComplexNumber1 * myComplexNumber2 print(myProduct) In this example, two complex numbers are defined: myComplexNumber1 and myComplexNumber2. Then both numbers are multiplied and the result is saved as myProduct. Finally, the result is printed. (-7+22j)

multiply strings

If one of the values is a string, Python will repeat the string as often as specified by the multiplier. # multiply strings repeat_once = 1 * "2" repeat_twice = 2 * "2" repeat_thrice = 3 * "2" print(repeat_once, repeat_twice, repeat_thrice) The first string is repeated once. The second string is repeated twice. The third string is repeated thrice. 2 22 222

multiply Lists

If one of the values is a list, Python will repeat the values in the list as often as specified by the multiplier. # multiply identical lists myList = [1, 2, 3] print(2 * myList) The list is repeated twice and the result is printed. [1, 2, 3, 1, 2, 3] It is also possible to multiply the elements of lists as shown below. # multiply elements of lists myList = [1, 2, 3] myFinalList = [] for n1, n2 in zip(myList, myList): myFinalList.append(n1 * n2) print(myFinalList) In this example, a filled list and an empty list are defined. Then the zip() function is used to zip myList and myList. The product of each multiplication is added to the myFinalList list. Finally, the myFinalList is printed. 1 * 1 is 1 2 * 2 is 4 3 * 3 is 9 [1, 4, 9] Instead of multiplying the list by itself, we can also multiply the elements of two different lists. # multiply elements of two different lists myList1 = [1, 2, 3] myList2 = [2, 2, 2] myList3 = [] for n1, n2 in zip(myList1, myList2): myList3.append(n1 * n2) print(myList3) Three lists are defined. Two lists include the elements to multiply and one empty list is used to store the results. The zip() function is used to multiply the elements and the append() method of myList3 is used to store the results. Finally, the list of results is printed. [2, 4, 6]

                
        

Summary


Click to jump to section