Python Forum

Full Version: Create X Number of Variables and Assign Data
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Good morning,

I'm trying to create a number of variables that is dynamic.

Lets say I have a string

sentence = "All work and no play makes Jack a dull boy."

and I count the number of words in the string using a counting scheme of some sort and arrive at a value of 10.

I then want to create 10 variables and store each separate word into a different variable.

I think I could use a function like this:

while i < num_vars:
var_name = ??? - I think I could just loop through numbers and concatenate for a name. Ie.. "var_" concatenated with i , then iterate i
var_value = ??? - Should I use some string split function in python, or assign to an array and use array functions?
exec(var_name + " = " + var_value)

Thanks again for the help and I hope this makes sense.
Don't try to dynamically create variables, because that will lead to code that's difficult to maintain. Instead, use a list if you want to keep items in order, or use a dictionary if you want to associate names with the values.
I'm just working through one of the tutorial exercises, not sure if it ever makes sense to store in variables for later reuse (days or weeks later), but I'm fairly new at this.

This code seems to do what I was looking for though.

sentence = "All work and no play makes Jack a dull boy."

print("The original sentence is: '", sentence, "'")

print("")

string_length = len(sentence)
print("length of string is: ", string_length)
         
delimeter = " "

string_array = [string_length]
string_array = sentence

#if empty string set modifier to 0
if string_length == 0:
    count_modifier = 0
else:
    count_modifier = 1

num_vars = string_array.count(delimeter,0)+count_modifier

print("The number of words in the sentence is: ", num_vars)

i = 0

var_assignment_string = ""

#Builds a string for assigning variable data from a list
while i < num_vars:

    var_name = "var_" + str(i)
    var_assignment_string = var_assignment_string + var_name + ","
    i = i + 1

var_exec_string = var_assignment_string + " = sentence.split(' ')"

exec(var_exec_string)


print(var_0)
print(var_5)
print(var_9)
Please, don't do this. Use proper data structure like list or dict.
By the way, there are plenty of odd things in this code you show
By the way, you can use indexes directly on the string, no need of lists, or dynamically created variables
sentence = "All work and no play makes Jack a dull boy."
delimiter = ' '

words = sentence.split(delimiter)
print(f'First word is: {words[0]}')
print(f'Sixth word is: {words[5]}')
Output:
First word is: All Sixth word is: makes
Hopefully I get better at this haha.

I think the next chapter in the book gets into that, I'll try to avoid being odd in the future LOL
More like this.
sentence = "All work and no play makes Jack a dull boy."
print(f"The original sentence is: '{sentence}'\n")

string_length = len(sentence)
print(f"Length of string is: {string_length}")
words = sentence.split()
word_dict = {f"var_{i}": word for i, word in enumerate(words)}
num_words = len(words)
print(f"The number of words in the sentence is: {num_words}")
# Use word_dict 
print(word_dict["var_0"])
print(word_dict["var_5"])
if "var_10" in word_dict:
    print(word_dict["var_10"])
else:
    print("The sentence does not have a eleventh word.")
Output:
Length of string is: 43 The number of words in the sentence is: 10 All makes The sentence does not have a eleventh word.
So as suggests before in post,i make dictionary and do not mess with dynamically variables hidden in globals() dictionary.
>>> word_dict
{'var_0': 'All',
 'var_1': 'work',
 'var_2': 'and',
 'var_3': 'no',
 'var_4': 'play',
 'var_5': 'makes',
 'var_6': 'Jack',
 'var_7': 'a',
 'var_8': 'dull',
 'var_9': 'boy.'}

>>> word_dict['var_3']
'no'
>>> word_dict.get('var_8')
'dull'
>>> word_dict.get('var_11', 'Value not in word_dict')
'Value not in word_dict'
Maybe this is the step in the lesson plan where you learn that having dynamic variables is required for some tasks. In lesson 2 you learn that Python already has a dynamic variable that does exactly what you want, and it is called a list.
What happens if a word repeats? What about punctuation? Lose the punctuation?

I think there are already modules for doing this kind of thing.

from collections import Counter
sentence = "All work and no play makes Jack a dull boy. Jack is a dull boy. Work makes him dull."
words = sentence.split()
wordCount = Counter(words)
Output:
Counter({'Jack': 2, 'a': 2, 'dull': 2, 'boy.': 2, 'All': 1, 'work': 1, 'and': 1, 'no': 1, 'play': 1, 'makes': 1, 'is': 1})
type(wordCount)
Output:
<class 'collections.Counter'>
wordCount['Jack']
Output:
2
I concur that dictionary or list is the way to go.

One way to create dictionary from sentence can be dictionary comprehension:

>>> sentence = "All work and no play makes Jack a dull boy."
>>> {f"var_{i}": v for i, v in enumerate(sentence.split())}
{'var_0': 'All', 'var_1': 'work', 'var_2': 'and', 'var_3': 'no', 'var_4': 'play', 'var_5': 'makes', 'var_6': 'Jack', 'var_7': 'a', 'var_8': 'dull', 'var_9': 'boy.'}
>>>