Utsuho Reiuji
Utsuho Reiuji

Reputation: 25

Why python handles varible strangely?

Interestingly enough, when I change the variable type first it resulted in a error of unsupported oprand type of adding str and int:

average = ['12','23','34','45','56','67','78','89','90','100']
avenum = 0

for each in average:
    int(each)
    avenum = avenum + each

However in this configuration the code will execute:

average = ['12','23','34','45','56','67','78','89','90','100']
avenum = 0
for each in average:
    avenum = avenum + int(each)

I am curious to know the difference between those two and why python ahandle them differently.

Upvotes: 0

Views: 83

Answers (3)

cdarke
cdarke

Reputation: 44394

int is the name of a class:

>>> each = 42
>>> isinstance(each, int)
True

In python we create an object of a given class using the general syntax:

object-name = class-name(constructor-parameters)

So when you do:

int(each)

you are creating a new int object but then not assigning a name to it.

each = int(each)

will call the int constructor using the str object referred to by each. This will return a new int object and the name each now refers to that object. The original str object has its reference count decremented and, if zero, becomes a candidate for destruction.

No str or int methods or functions change those objects, they return a new one, since those objects are read-only, or immutable.

That's the theory anyway. Implementations of python might optimise int and str because they are such common objects, but that's a detail that should be invisible to the programmer.

Upvotes: 1

Joe Iddon
Joe Iddon

Reputation: 20434

From the docs, we see int() does not modify the item passed to it (like, for instance, list.insert) because a new integer object is returned.

Return an integer object constructed from a number or string x, or return 0 if no arguments are given.

The reason for this is that integers, strings, tuples and other types are immutable so cannot be modified - instead a new instance must be made. On the other hand lists, sets and other types are mutable so their values can be changed which is why they have methods which don't return the modified list, but instead modify it in place.

Upvotes: 2

Geno Chen
Geno Chen

Reputation: 5214

int(each) will not change the value or type of each, the return value of int(each) is dropped. So the line int(each) in the first code have no use to the later execution.

Upvotes: 2

Related Questions