ThatCampbellKid
ThatCampbellKid

Reputation: 533

Variable Assignments in Python

I'm new to programming and python, and I'm looking for the best way to store information in my program.

I'm looking to store multiple values for each item, but don't know what the best way might be for this. It would be something like:

number: x position, y position, color

The problem I have is that I may have 1,000,000 numbers... Do I make a million dictionaries? And if I do, would I efficiently be able to call on all of them?

Upvotes: 0

Views: 77

Answers (1)

Pouria
Pouria

Reputation: 1091

There are 2 types of arrays in Python. list() and tuple(). The former is mutable, whilst the latter is immutable. For the purpose of this work, you can assume that list() may later be modified, whilst tuple() may not.

To be honest, 100k data is not that much to handle by Python. A simple ordinary differential equation would produce more than that!

So, you can do it like this:

Store your individual arguments in tuples, so as to ensure (a) data integrity, and (b) memory optimisation.

var = (35, 56, (123,23,213))

Then add your var to a list containing all your data.

data_container = list() 
data_container.append(var)

.append(var), however, is not the most efficient way to do it; for every time you append your data, you force a copy of the entire data in the RAM. A better way would be to initialise your list beforehand, then insert your data to it later on. Though for this, you need to know how much data input your will receive, or at least be willing to set a maximum!

This works as follows:

data_container = [[]]*int(1e5) # A list of 100,000 rows.

Following which, you may use a function to add to this list. This is a simplistic example. Although I'm passing a single numeric value, you can have anything you want. Don't forget to create a back door to break out of the loop! In this instance, the back door is a the value of input not being numeric (i.e. be a string, or just empty). Also, I am not handling the maximum inputs in here, nor am I using any conditions. Once you reach the maximum number of rows, you will end up with an IndexError. You can either handle this error and display a "maximum reached" message, or increase the capacity of your list by concatenating it to another list with extra rows. Your choice!

data_container = [[]]*int(1e1)
max_capacity = len(data_container)
ind = 0

def add2container(index, data):
    data_container[index] = data
    index += 1
    return index


while True:
    x = input('Enter x: ')
    if a.isnumeric():  # A Python 3 feature. 
        ind = add2container(ind, float(x))
    else:
        break

I hope this answers your question. But if not, please go ahead and ask / explain further.

Upvotes: 1

Related Questions