0

The output of my python program is a list (G) which has almost 100000 elements. I want to use these elements in the later part of the program. How can I save my list (G) so that I don’t have to run the program again and again?

piRSquared
  • 285,575
  • 57
  • 475
  • 624
  • 6
    Any number of ways. Maybe `pickle` is what you want. Maybe you want `sqlite`, `shelve`, a `csv`, `json`, a text file. Really, you have to be more specific in your requirement. – roganjosh Jun 13 '18 at 18:56
  • is this list(G) generated by some logic or you just loaded it? – rawwar Jun 13 '18 at 19:01
  • I want to access the elements of saved list in other python programs. – Shashank Ranjan Jun 13 '18 at 19:03
  • Generated by some logic which takes almost three hour to run on my PC. – Shashank Ranjan Jun 13 '18 at 19:04
  • It's still too broad. Maybe you could use `HDF5`. Maybe you could use `redis`. No answer will amount to more than "you need to save the data" because you're not giving any constraints or reasons why some approaches are undesirable. Should it be in-memory or on disk? – roganjosh Jun 13 '18 at 19:07

4 Answers4

1

You can do like this

list=[1,2,3,4,5,6]
thefile = open('test.txt', 'w')
for item in list:
  thefile.write("%s\n" % item)
Manoj Kumar Dhakad
  • 1,862
  • 1
  • 12
  • 26
  • 1
    Well, you _could_ but that's one of a myriad of ways, with no way really to whittle it down. If security isn't a concern so much, `pickle` would be better. The question is too broad as it is. – roganjosh Jun 13 '18 at 19:04
1

Personally I like to use pickle

To store as a pickle object

import pickle
a = {'your_list': [1,2,3,4]}
with open('filename.pickle', 'wb') as handle:
     pickle.dump(a, handle, protocol=pickle.HIGHEST_PROTOCOL)

To read from pickle object

import pickle
with open('filename.pickle', 'rb') as handle:
    a = pickle.load(handle)
print a # a is now {'your_list': [1,2,3,4]}
sP_
  • 1,738
  • 2
  • 15
  • 29
1

pickle enables you to save your python object to your disk. Without running your first program, you can just load this pickle file and use it in another program by just calling the load function.

ThReSholD
  • 668
  • 10
  • 15
0

Here i got your question you have to use data or arrays in onother program is it?

For that you didn't have to use your physical memory you can easily create module of your program and use this module in second program by importing first module which decrease space complexity and you can use specific value in second program with loading all list or array which also decreases time complexity of execution.python module

And if you want to store data for other purpose then you can use local file storage or sqlite. File i/o inpython

manan5439
  • 898
  • 9
  • 24
  • 1
    It is very hard to understand this answer. Can you get a friend to help you rewrite it in better English? – PM 2Ring Jun 13 '18 at 19:36