Mansuy Thomas
Mansuy Thomas

Reputation: 3

Append list called with iterate

I have a simple issue with my code in Python 3.6.

I am reading a csv and storing int values in a list called Total. I ask Python user to enter a number n=.. (in this example n=9). I create n (9) empty list with :

for j in range (1,n+1):
    command=""
    command="list"+str(j)+"=[]

Now, I have list1, list2, ... list9

Then, I want to append these lists by reading Total starting at different elements and reading each n (9) elements.

For example:

list1=[Tot[0],Tot[8]...] list2=[Tot[1],Tot[9],...]

To do so, I want to something like

for k in range (0,n):
    for a in range (0+k,len(Total),n):
        listk.append(Total[a])

My problem is here, Python doesn't recognise the integer in listk such as:

list1, ... list9

Is there a certain way to do it ? Maybe by using a class ?

Upvotes: 0

Views: 58

Answers (1)

yuvgin
yuvgin

Reputation: 1372

For your problem I suggest using a dictionary. A dictionary is a type of data structure in python that allows to store pairs of information - for example lists and their names. This way you can create n separate named lists, store them all inside one dictionary, and append them as necessary. To start at different indices, I make use of the modulo operator.

This should do the trick:

# shorthand syntax for creating a dictionary with n empty lists: list1,...,listn
    lists = {"list" + str(i + 1): [] for i in range(n)}
    for k in range(n):
        list = lists.get("list" + str(k + 1))
        for j in range(n):
            list.append(Total[(j + k) % n])

A few sidenotes:

It seems you have a few misunderstandings concerning Python syntax. When you declare the variable "command" inside your loop, Python is saving a pointer to a specific place in stack memory. However you are inside a loop, so "command" is overwritten in every iteration of the loop, and the old pointer is lost.

The following line:

command="list"+str(j)+"=[]

is invalid in Python. The syntax to create lists using square brackets is:

variable = [item1, item2, item3] # or variable = [] for an empty list

You cannot mix between strings and list creation in the way you attempted to.

Upvotes: 1

Related Questions