How would I assign a variable to each value in a list

I want to assign a variable but the same variable just increased by one to each value in a list so for example my_list=[[aa],[ab],[ba],[bb],[bc],[cb],[cc],[cd]] and I want d to be the variable and have d+=1 to proceed through the list for example the output to look more or less like, value[0]=d0, value[1]=d1, value[2]=d2, value[3]=d3, value[4]=d4, value[5]=d5, value[6]=d6, value[7]=d7.

def my_list():
    my_list=[[aa],[ab],[ba],[bb],[bc],[cb],[cc],[cd]] #list of values
    for d in my_list:
        d+=1 #? i don't know? how could i do this?

Upvotes: 2

Views: 142

Answers (2)

Rushy Panchal
Rushy Panchal

Reputation: 17532

One way I thought of doing it:

def my_list(n):
   my_list, my_num, my_var = [], 0, '' #multiple assignment of variables
   for my_num in range(n + 1): #second argument is exclusive, this implies (0, n + 1)
      my_var = 'd' + str(my_num)
      my_list.append(my_var)
   return my_list

Alternatively, you can use dictionaries (same idea but a tad bit different):

def my_dict(n):
   my_dict, my_num, my_var = {}, 0, ''
   for my_num in range(n + 1):
      my_var = 'd' + str(my_num)
      my_dict[my_num] = my_var
   return my_dict

Where it would result in the key for each entry as my_num and the value is my_var. You can replace 'd' with anything really, as long as it is a string. If it is not formatted as a string, and my_num is an integer or a floating-point number, it will add them together (3 + 7 would result in 10, not 37), not concatenate them.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1122142

Perhaps you are looking for a list comprehension?

value = [d[0] for d in my_list]

A list comprehension lets you process each element of an iterable to produce a new list. The above example takes the first element of the nested lists, adding each to a new list. Your input list would then be transformed to:

[aa, ab, ba, bb, bc, cb, cc, cd]

Upvotes: 1

Related Questions