0

I'm trying to use a for loop to assign values to variables - in this case the variables are all called: 'die1', 'die2', 'die3', etc.

import random for i in range(5): die[i] = random.randint(1,6) 

What i'm trying to achieve is ending up with 5 variables assigned with a random number. I've tried a few different ways but end up with either 'die' variable not been assigned or that I'm not able to use 'i' or another variable that I count up.

4 Answers 4

2

For your interpreter, die1, die2, etc. are unrelated entities. If they should be grouped as in your case, consider a list:

die = [random.randint(1,6) for _ in range(5)] 

Now you can access die[0], die[1], etc. If you really need independent variables, you can use:

die1, die2, die3, die4, die5 = [random.randint(1,6) for _ in range(5)] 

This, however, will raise an error if the number of variables on the left does not match the length of the list/tuple on the right. For flexibility reasons, I would recommend using a list.

Sign up to request clarification or add additional context in comments.

5 Comments

Is there any possible way to not use a list, and just store them as seperate variable? I have a list later that looks like this: dice = [die1, die2, die3, die4, die5] And later functions are called as such: dice[i] With 'i' being controlled through a for loop
This is the elegant solution.
@Tym You could just create your dice list as indicated here. There should be no justifiable need to first create independent variables if you then stuff them into a list anyway.
Thanks for the update :)! The reason I'm using them is just because I'm not very confident with lists... Poor excuse, I know...
@Tym: Well you should get confident by practicing using lists! :) Write lots of tiny programs that use lists until you're comfortable with how they behave. Lists are very important, especially in Python, which has several powerful features for handling lists. When code has a bunch of numbered variables like die1, die2, die3, die4, die5 it almost always should be using a list or tuple (or possibly a dict) instead. Using a bunch of numbered variables makes the code bigger and more confusing than it needs to be, making it harder to develop & maintain.
0

I'd suggest making a fixed size list that you assign to so it doesn't grow each time you call append.

import random die = [0] * 5 def roll(): for i in range(5): die[i] = random.randint(1, 6) 

Now you can call roll and the die list is updated.

6 Comments

Why is it bad for the list to grow? Isn't it worse to fill up memory with zeros unnecessarily?
@zondo I am assuming he wants a list of 5 numbers. If using append each call to roll will append 5 new numbers to the list thereby growing it. The list of five numbers (initially zero) is updated with new values each call to roll. So there is no memory fill and no new list is created every time.
No new list is created anyway. If you don't like the idea of a growing list, use a list comprehension: die = [random.randint(1, 6) for _ in range(5)]
@ThomasChristensen Actually, append does not create a new list, at least not every time ;) . Appending is O(1): wiki.python.org/moin/TimeComplexity
@zondo list comprehensions creates a new list each time it is evaluated right?
|
0

Assuming the goal is to fill a list named die, then you can define it and append the integers at each iteration:

import random die = [] for _ in range(5): die.append(random.randint(1, 6)) 

If you mean to different variables, you can define them dynamically using vars:

import random die1, die2, die3, die4, die5 = [0] * 5 for i in range(5): vars()['die{}'.format(i)] = random.randint(1, 6) 

The line defining the local variables is not mandatory though it'll be easier to work with in an IDE.

If you mean to the first part, or to the second part with few variables, I think that schwobaseggl's solution is more elegant.

2 Comments

Thanks for the response! Mind me asking why you used '_' in the first for look for the looping variable, but 'i' for the second? Also - what's the importance of including vars() in the second part?
In the first loop, i is not used - a common convention in python is to name this kind of variables with _.
0

If the number of variables are large it might be not possible to mention all variable names at the beginning. Instead they could be created at each iteration of the for-loop and stored in a dictionary as keys while the random numbers associated with them can be stored as their values in the dictionary.

You could use string joining for creating variable names eg 'die'+'1' = 'die1' . If you call 'die1' as 'n' then you add a new key to the dictionary as Dict[n]=randint(1,6) where randint(1,6) is the value corresponding to 'die1'. This way you can easily use these variables for mathematical operations.

from random import randint Dict={} count=1 for i in range(5): n='die'+str(count) DICT[n]=randint(1,6) count=count+1 print DICT print DICT['die1'],DICT['die2'] print DICT['die1']+DICT['die2'] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.