Lei Hao
Lei Hao

Reputation: 799

Dynamically accessing variables in python

There are 9 texts called text1, text2, ... text9. A function is defined as follow.

def lexical_diversity(text):
    return len(set(text))/len(text)

I want to call the function for all 9 texts with following code. But the outpu is wrong.

for i in range(1,10):
    a='text'+str(i)
    print(lexical_diversity(a))

My output is

0.8
0.8
...
0.8

If applying the function to text1, I get following result.

>>>lexical_diversity(text1)
   Out[37]:0.07406285585022564

So which part goes wrong?

Upvotes: 0

Views: 2640

Answers (2)

ricristian
ricristian

Reputation: 536

Python3

def lexical_diversity(text):
    return len(set(text))/len(text)
lista = []
for i in range(1,10):
    lista.append("text%d" % i) 
for resVal in lista:
    print(resVal) 
    print(lexical_diversity(resVal))

Upvotes: 0

cs95
cs95

Reputation: 402463

You should understand that a = 'text' + str(i) does not magically bestow upon a the value of whatever is contained inside the variable text1. Instead, a is assigned to the string "text1". The two are not the same.

Given the names, you should probably consider storing your texts in a list:

texts = [text1, text2, text3, ...]

And now,

for a in texts:
    print(lexical_diversity(a))

Upvotes: 4

Related Questions