Haytham
Haytham

Reputation: 502

how to retrieve text from a variable stored in a list python

So I am trying to store multiple variables in a list, each variable contains text. After that, I would like to perform some analysis on the text which is stored inside the variable that is stored in the list.

Code:

my_list = list[]

var_1 = 'I have lots of text'
var_2 = 'I have even more text'
var_3 = 'but wait there is more'

my_list.append('var_1','var_2','var_3')

for var in my_list:
    x = package.function('var')
    print x

what ends up happening is that the function is performed on the variable name not the text that is stored inside it. Thanks for your help in advance.

Upvotes: 0

Views: 173

Answers (3)

user5469070
user5469070

Reputation: 23

As a new Python learning, i found some issue in your code.

Issue 1. This is how you declare a list in python.

my_list=list()

Issue 2. list.append method takes only 1 argument. So you can not pass all 3 variables at a same time.

 my_list = list()
 var_1 = 'I have lots of text'
 var_2 = 'I have even more text'
 var_3 = 'but wait there is more'

 #append all variables in list:
 my_list.append(var_1)
 my_list.append(var_2)
 my_list.append(var_3)

 #first way to print:
 for var in my_list:
    print var

 #second way to print:
 print my_list

 #third way to print:
 for idx,item in enumerate(my_list):
     print idx ,":", item

Upvotes: 1

idjaw
idjaw

Reputation: 26600

Your problem is that you are storing the string representation of your variable names:

my_list.append('var_1','var_2','var_3')

Furthermore, you cannot use the append like this. What you want to do is actually put in your variable names like this:

my_list = [var_1, var_2, var_3]

Finally, you are accessing your list index as 'var' in your loop:

for var in my_list:
    x = package.function('var')
    print(x)

to this:

for var in my_list:
    x = package.function(var)
    print(x)

Upvotes: 1

inspectorG4dget
inspectorG4dget

Reputation: 114035

var_1 = 'I have lots of text'
var_2 = 'I have even more text'
var_3 = 'but wait there is more'

my_list = [var_1, var_2, var_3]

for var in my_list:
    x = package.function(var)
    print x

Upvotes: 1

Related Questions