2

I have a list that contains one or many items:

fruits = ['apple', 'orange', 'pear'] #or could be one or many

I want to create variables depending on the number of items: Code:

    for i in range(len(fruits)):
        "Fruit".format(i) = fruits[i]

I want to obtain as:

    Fruit1=apple, Fruit2=orange, Fruit3=pear

Any help how I can get this?

P1ng3r
  • 45
  • 6
  • possible duplicate of [How can you dynamically create variables in Python via a while loop?](http://stackoverflow.com/questions/5036700/how-can-you-dynamically-create-variables-in-python-via-a-while-loop) – Dan Oberlam Feb 27 '15 at 20:23
  • First and foremost, your assignment is backwards. – Malik Brahimi Feb 27 '15 at 20:28
  • His/her assignment isn't backward. He/she wants to create multiple named variables from the items in the list. The syntax in the question won't work, and it's a bad idea to begin with, but that's why he/she asked the question. – kindall Feb 27 '15 at 20:46
  • The reason why I want it like that is because, I want to be able to print it depending on the number of elements. print ("Fruit".format(i)) – P1ng3r Feb 27 '15 at 20:48

2 Answers2

1

As a proper way for such tasks you can use a dictionary :

>>> fruits = ['apple', 'orange', 'pear']
>>> d={"Fruit{}".format(i):j for i,j in enumerate(fruits,1)}
>>> d
{'Fruit1': 'apple', 'Fruit2': 'orange', 'Fruit3': 'pear'}
>>> d['Fruit1']
'apple'

Note that if you use a data structure like dictionary for your problem you will get a lot of advantages like, that you can access to all of your values with dict.values() and all of the keys with dict.keys() also it could be more easier for interaction with another data structures!

>>> d.keys()
['Fruit1', 'Fruit2', 'Fruit3']
>>> d.values()
['apple', 'orange', 'pear']
Mazdak
  • 105,000
  • 18
  • 159
  • 188
0

First and foremost, your assignment is backwards. You're trying to set a list index in a string instead of a string in a list index. Otherwise, I suggest using the enumerate function. Don't be tripped up by my formatting, there are my ways to do so in Python.

for i, j in enumerate(fruits):
    fruits[i] = "Fruit%d=%s" % (i + 1, j)
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70