jlm699 320 Veteran Poster

have code snippet.any ideas?


for clust in clusters: #for each name in a list of names i have
outNM = "fam" + str(count) + ".mcl.fas" #a series of files i want written to
outFL = open(outNM, 'a')

for c in clust: #for each letter in my list of names that i have
c = c.rstrip()

for c in clust:
outFL.write(">" + dict[c] + "\n") write each name to my file i have open.

but it doesnt want to work.

Can you clarify what isn't working? I'm going to take a wild guess and say that dict[c] is failing for "c" not being in the dictionary. In your first for loop you say c = c.rstrip() but then you don't save the updated c back to clust for the next for loop. What you should do is just a single for loop like this:

for c in clust:
	outFL.write(">" + dict[c.rstrip()] + "\n")

See if that helps. There are other ways to improve your code (like don't name your dictionary dict as that's a reserved word in Python), but that's for another discussion

jlm699 320 Veteran Poster
...### Turn the message into a number list
###
#####################################################
## Helped by masterofpuppets at daniweb.com forums
def letter_number(message_raw):
    message_raw = message_raw
    message = string.lower(message_raw)
    letters = list(message)
    alphabet = " abcdefghijklmnopqrstuvwxyz"
    message_number = []
    for letter in range( len( letters ) ):
        if letters[ letter ] in alphabet:
            for i in range( len( alphabet ) ):
                if letters[ letter ] == alphabet[ i ]:
                    message_number.append( i )
                    break
    letter_number.message_number = message_number
    letter_number.message = message
#######################################################

All of that can be turned into this:

def letter_number_alt(message):
    alphabet = " abcdefghijklmnopqrstuvwxyz"
    message_number = [alphabet.index(letter) for letter in message.lower() if letter in alphabet]

Also, notice you don't need to import string and use string.lower(string_to_lower) , you can just use string_to_lower.lower()

jlm699 320 Veteran Poster

It didn't work,
I tried: self.opframe = OptionFrame(MyFrame(self), -1, "") But in commandline the program keeps running..

If your main frame is creating this OptionFrame (ie, if the "self" in the above code is actually the instance of MyFrame) then you should be doing just self.opframe = OptionFrame(self, -1, "") . See if that gives you any joy

jlm699 320 Veteran Poster

I mean the "X" button =)
I open it with:

self.opframe = OptionFrame(None, -1, "")
self.opframe.Show()

I haven't done any work in wxPython for over two years but perhaps it's related to opframe having a parent of None. Perhaps its parent should be the main frame?

jlm699 320 Veteran Poster

Wow, that code is pretty long!

Here's a shortened version:

import string

# Strings are already iterable so we don't need to convert to list
message = raw_input('Enter a string: ')
# Make a string of a space plus all the lower case letters (the first
## 26 indices of the string.letters object is all lowercase).
my_letters = ' ' + string.letters[:26]

message_number = []

# Just iterate over the message, we don't care about index
for each_char in message:
    message_number.append(my_letters.index(each_char.lower()))

print message_number
raw_input('\nPress any key to exit...')

If there's anything you don't understand please don't hesitate to ask.

jlm699 320 Veteran Poster

where can I find a reference for what the different parts of the command means. Anyone know where I can find this information for these an similar commands?

This was found through the tutorials section on the Komodo Edit project hosted on active-state.

jlm699 320 Veteran Poster

If I start my program and choose to show the option frame, it will show it, but if I now close both frames the program keeps running in the background..

It would be helpful if you showed us the relative code (ie, how you're opening the Optionframe and how you're destroying/closing it).

When you say "close both frames" do you mean click the "X" window button? Or does something in your code close them?

jlm699 320 Veteran Poster

Using a leading double underscore on a class member makes it psuedo-private; however with persistence you can still see/access the object (it's just not immediately apparent). There is no such thing as "private" in Python.

>>> class A(object):
...     _Member_A = 'a'
...     __Member_B = 'b'
...     
>>> dir(A)
['_A__Member_B', '_Member_A', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
>>> A._A__Member_B
'b'
>>>

As you can see, leading double underscored objects get obfuscated with the class name.

jlm699 320 Veteran Poster

i am having diff in understanding this code..i am supp to do it in python

for qid,query in "as2.qrys": 
       for word in query: 
         docs = set(index[word]) 
         for doc in docs: 
           number_of_matched_words [doc] ++ 
       for doc in matches: 
         if number_of_matched_words[doc] == length(query): 
           print qid, 0, doc, 0, 1, 0

Is this psuedo-code that you're supposed to translate into Python?

jlm699 320 Veteran Poster

28 Minutes Ago | Add Reputation Comment | Flag Bad Post

Hah, that's awesome...

One last problem with my script, it returns this error message...

Traceback (most recent call last):  File "C:/Python26/Renamer 3", line 23, in <module>    os.rename(fname, b)WindowsError: [Error 2] The system cannot find the file specified.Traceback (most recent call last):
  File "C:/Python26/Renamer 3", line 23, in <module>
    os.rename(fname, b)
WindowsError: [Error 2] The system cannot find the file specified.

This indicates that the "from" file is not located at C:/Python26/Renamer 3... Is that correct? C:/Python26 is likely the current working directory (it's where python.exe is located). And since you just gave the filename as Renamer 3, it assumed this file was in that directory.

To avoid this you can use an absolute path (ie, C:/Foo/Bar/Choo/Renamer 3 or wherever the file is located)

jlm699 320 Veteran Poster

So you want to use the value of Templng for the default value of the to parameter in the translate function?

jlm699 320 Veteran Poster

If you want to use backslashes in a path name for loadtxt (or savetxt), the you need to put in double backsplashes so:
'c:/users/ross/desktop/radiograph_data.txt'
becomes:
'c://users//ross//desktop//radiograph_data.txt'

Those are forward slashes, which do not need to be escaped (the escape character is \, which is backslash)

jlm699 320 Veteran Poster

It's hard to tell whether you did this or not since you didn't give us all your code, but I'm assuming that before assigning to Templng you used global Templng to let the local scope know you meant to use the global variable and not just create a new local one?

Or maybe that's the whole problem.

jlm699 320 Veteran Poster

What are you asking for help with?

jlm699 320 Veteran Poster

Can you give me an example?

Better yet: I'll give you about 57,900 examples

jlm699 320 Veteran Poster

How do I call the program from the command line?

Type your python command (*if you haven't set it up you'll need to use the full pathname to python.exe or pythonw.exe), then the name of your script, then the command line arguments... here's an example:

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\>
C:\>edit cmd_args.py

C:\>C:\Python26\python.exe cmd_args.py these are command line args


C:\>

Note: The cmd_args.py simply contained the following:

import sys
print sys.argv

In my environment I've set the "python" command to point to "C:\Python26\python.exe", that way when I'm in the cmd line I can just type "python <script_name> [args]"... it's much faster.

jlm699 320 Veteran Poster

3) What do you mean I ask for it and then it's not passed on to tile? 'n' is used in your next suggestion? Maybe I'm not understanding your statement?

This is the section he's referring to:

def main():
    filename=raw_input ("Gimme a picture.")
    n=raw_input ("How many times would you like it tiled?")
    img=Image.open(filename)
    tiled=tile(img)
    tiled.show()

You store the user's input into the object n ; however after that you never use it. Inside your tile() function you do create a new n, however even if you removed the n = 0 step, you'd get an error because n does not exist in the tile function, only in your main function. What you would want to do is pass it to the tile function... something along the lines of tile(img, n) .

If you use m==0 it will give you False unless m is zero.

Just to further explain the difference between = and == :

>>> m = 0
>>> m
0
>>> m == 0
True
>>> m = 5
>>> m
5
>>> m == 0
False
>>>

As you can see, a single ( = ) is for assignment. A double ( == ) is for comparison a.k.a. "is equal to", and returns true or false.

jlm699 320 Veteran Poster

You have a number of issues in your code revolving around scope.

Here are the first few that jumped out at me:

1) In your dig_sum function, you refer to i but never define it (in your while loop). Perhaps you're referring to the i from the avo function or from the global scope. If that is the case you should be passing it to the function specifically, not relying on the global value. Otherwise you need to define a starting point and somehow increment it inside the while loop.

2) Same as above but in the avo function you're referencing and modifying the list named arr. Again, if you really want to modify this list you should be passing it and not using globals.

Note: number 1 is the reason that your program hangs. You don't modify the value of i so that while loops simply runs forever.

EDIT: Here's a cleaner way of doing a digital sum using list comprehension:

>>> def dig_sum(n):
...     ''' Prints the digital sum of number n. '''
...     return sum([int(each_numeral) for each_numeral in str(n)])
...     
>>> dig_sum(52)
7
>>>

And to break that out:

>>> def dig_sum(n):
...     ''' Prints the digital sum of number n. '''
...     dsum = 0
...     for each_numeral in str(n):
...         dsum += int(each_numeral)
...     return dsum
...     
>>>
jlm699 320 Veteran Poster

Welcome to the forums.

EDIT: OP Updated post with Code tags

Also, when asking about a specific error you get, it would help if we could see the entire traceback (which helps to identify exactly what line the error occured on). Seeing as you have an indexing error, we can narrow down where the error occurred, however it's hard to pin-point exactly what the problem is.

Can you please repost with the entirety of the traceback that you get?

EDIT 2: Also note that in Python ^ is the bit-wise XOR operator. To use "power of" 2 use **

jlm699 320 Veteran Poster

The tkinter tutorial at tkdocs (http://www.tkdocs.com/tutorial/firstexample.html) shows these two lines at the beginning of every example.

from tkinter import *
from tkinter import ttk

Doesn't the first line import everything in the tkinter module? if so, why bother writing the second line?

When performing an import * in Python, you as a developer actually have power over what is included in that "import all" statement. By populating your package with either an __all__.py file or an __all__ object within the package's code you're able to specify only particular objects to import.

Read up on this "import all" business here in the Python docs (which specifically talks about the __all__ convention)

EDIT: So what I'm trying to say is that the tkinter package probably doesn't have this ttk thingamabob included in the import all hubbub.

jlm699 320 Veteran Poster

Hi, While running my Python Script I am getting "org.python.core.PyInstance" ERROR. I am not getting why this ERROR is coming. Please help......

With the limited information that you've provided my only guess would be that your Python installation is corrupted. You should reinstall.

jlm699 320 Veteran Poster

When you return an object it isn't just automagically added to the current namespace... you need to actually store it in something.

All you'll need to do is say graph = plot_it(...) , savvy?

jlm699 320 Veteran Poster

wow thanks for that dude I was actually wondering how to create private variables in Python. That really helped :)

Yes, but be forewarned it's psuedo-private. You can still see and access the variable, it's just obfuscated with the Class name. Look:

>>> class Cpriv(object):
...     def __init__(self):
...         self.__privy = 'I am hidden'
...     
>>> C = Cpriv()
>>> dir(C)
['_Cpriv__privy', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
>>> print C._Cpriv__privy
I am hidden
>>>
jlm699 320 Veteran Poster

suppose i have 10 different functions.

i generate a random no. between 1 to 10.
depending on its value i want to call the fucntion.
eg. no. 3 call func, no. 8 calls func 8... etc.
how do i do it using a loop without using the if else statement as it makes the code too long.

A dictionary. The key is the number, the value is the function.

Generate random number, then do something like my_function_dict[my_random_number]() . Get it?

EDIT: To illustrate:

>>> def funcA():
...     print 'A'
...     
>>> def funcB():
...     print 'B'
...     
>>> def funcC():
...     print 'C'
...     
>>> func_dict = {1:funcA, 2:funcB, 3:funcC}
>>> random_number = 2
>>> func_dict[random_number]()
B
>>>
jlm699 320 Veteran Poster
for i in range(len(dict)):
        dict[i] = dict[i][0:len(dict[i])-2]

What is that? What are you doing?

EDIT: Also remember that dict is a reserved word in Python I suggest that you change the name

jlm699 320 Veteran Poster

I write : print tag
it goes ok...

How about print ' || '.join([each.string for each in tag]) ... I've never used BeatifulSoup so I don't know about the whole tag.string thing that you're doing...

jlm699 320 Veteran Poster

Here is my code.
If I use forloop to write, it got error:
Traceback (most recent call last):
File "m.py", line 20, in <module>
f.write(tag.string)
TypeError: argument 1 must be string or read-only character buffer, not None


HOWEVER, if I don't use for loop, instead
write as : f.write(tag[1].string)
it is ok, WHY??


from BeautifulSoup import BeautifulSoup
import re
import os
import os.path
import urllib2

outfile='out.txt'

file = urllib2.urlopen("http://www.tripadvisor.com/ShowUserReviews-g294217-d305813-r49043831-Langham_Place_Hong_Kong-Hong_Kong_Hong_Kong_Region.html#REVIEWS")

soup = BeautifulSoup(file)
tag=soup.findAll(id=re.compile("^review"))

if os.path.isfile(outfile):
  os.remove(outfile)
f=open(outfile, 'a')


for i in range(0,5):
  f.write(tag[i].string)

Try inserting a print tag trace statement right before the for loop to make sure all elements in tag are actually strings...

jlm699 320 Veteran Poster

how can I change the permission setting?
I have the root account password.
I tried your method, now I can write in home directory, but not others.

You would use chmod with the target being the directory

That or simply login as root before executing the script.

jlm699 320 Veteran Poster

I use opensuse

Ok, so it's most likely that the folder you're trying to open the file in doesn't have write permissions for the user that is running the python script. You could either run the script as root or simply write the file to your home directory with ~/ instead of ./

jlm699 320 Veteran Poster

What platform is this? Windows XP, Ubuntu Linux, Mac OSX, etc?

There's a number of possibilities here. Most likely the folder you're working in doesn't give you write permissions.

jlm699 320 Veteran Poster

The functions work but it prints "unrecognised input" even though one of the if statements has been completed.

What functions?

The first code is not working because you're not iterating over your input anymore.

The second code is not working because your indentation is royally screwed up. Everything should be within the for loop.

jlm699 320 Veteran Poster

Sorry, i need the try except statements.

Unless your teacher is specifically telling you to use them in this manner, you really don't. And if he/she is, then I feel bad for you because your teacher is a terrible programmer.

If you're required to use them, then at the very least you should be printing any exception values like so:

try:
    # Massive try block here
except:
    print sys.exc_value
    sys.exit()

That way at least you'll have a small clue as to why your program is failing, but really you should print out the entire traceback.

I don't really understand what you mean. Could you link me to more information or explain in more detail? Thanks.

It would be something like this:

my_number = ''
for each_char in usr_input:
    if each_char in numbers:
        my_number += each_char
    else:
       stack.append(int(my_number))
       my_number = ''

Does that clear it up? Or was there something else that you didn't understand?

jlm699 320 Veteran Poster

In the future, please use code tags when posting code. It will allow the forum members here to read your post easily and will give you answers quicker (and of better quality).

Now I will repost your code with code tags so you can see the difference:

a=2
b=3
def functionA(a,b):
    c=a+b
    return c
def functionB(c)
    answer=c+1
    return c

how can I just call functionB

You need to call your functions. All you've done is defined them. To call a function you use the function identifier, followed by parenthesis. If the function has required parameters (which both of yours do), you need to provide those inside the parenthesis. If a function returns values (which both of yours do), you need to "catch" the return into some type of container.

And one final thing: in functionB you are storing c+1 into the object called answer; however you fail to return your "answer" and are just returning the original value of c.

jlm699 320 Veteran Poster

My first suggestion is to remove the giant try/except block. If you make a syntax error your program will quit and never tell you the reason why. That is extremely poor Python coding and opens the door for you to create debilitating issues in your code.

Now, in order to support numbers > 9 you'll need to basically append each numeral onto a string before doing your int() conversion.

An easy way to do this would be to have a string container... we'll call it my_numbers . In your if mystr in numbers statement, you'll be doing string concatenation (ie, my_numbers += mystr ) instead of int conversion. Then, in each of your "operator" cases, you'll take the previous my_numbers object, convert it to an int, add it to your stack, and then clear the object with my_numbers = '' .

That's only one possible way to do it... Your most efficient method would be using regular expressions, but that's probably way beyond the scope of your lesson.

jlm699 320 Veteran Poster

I'd look into beautifulsoup if you're looking to break this thing down into an object hierarchy type structure. I haven't used it much, but I know there's plenty of examples on this site of how to implement it.

jlm699 320 Veteran Poster

The method os.getcwd() can only ever return a single string. There's ever only one current working directory, so when you're saying for d in os.getcwd() , you're actually iterating over the string character by character. What you really want is just generators = os.walk(os.getcwd())

jlm699 320 Veteran Poster

is it possible to search a multi dimensional list for a certain letter then print out where that letter is?
i know u can use list.index() to find a letter but i could figure out how to do it with multi dimensional lists.

thx in advance

Something like this perhaps:

for idx_i, each_sublist in enumerate(main_object):
    for idx_j, each_string in enumerate(each_sublist):
        if each_string == my_letter:
            print 'Found %s at %s, %s' % (my_letter, idx_i, idx_j)

That could possibly work for you, otherwise you'll need to be a little more clear. Example input/output would help to define a way to solve this

jlm699 320 Veteran Poster

If you search the forum you'll see this question has been asked a bajillion times.

Here's an example from earlier today.

jlm699 320 Veteran Poster
if player[0] != "r" or player[0] != "p" or player[0] != "s":
        print "incorrect choice entered"

Just a minor logic error. This should be:

if player[0] != "r" and player[0] != "p" and player[0] != "s":
        print "incorrect choice entered"
jlm699 320 Veteran Poster

Not exactly, I'd like to take the values that are being sorted on and put them into a new list/dict etc.

For example, extracting only these values from the dictionary above:
new_list = ('2.5','3.5','3.9','4.0','3.1')

Okay... how about this:

>>> data_dict = {
... '1234': ['Matt', '2.5', 'CS'], 
... '1000': ['John', '4.0', 'Music'], 
... '1023': ['Aaron', '3.1', 'PreMed'], 
... '1001': ['Paul', '3.9', 'Music'], 
... '9000': ['Kris', '3.5', 'Business']
... }
>>> [data[1] for data in data_dict.values()]
['2.5', '3.5', '3.9', '3.1', '4.0']
>>>

That's just a quick list comprehension that will extract the second element (at index 1) from each list (which is stored as the "value" part of each dictionary entry.

jlm699 320 Veteran Poster

Wow, thanks a lot! The idea of using a method didn't cross my mind. But for one of my test cases I changed the numbers to two-digit numbers and now the first two-digit number in a list becomes "ripped" as in {a:}. I am just wondering how does this happen? How come it messes up only the first number?

Because a string is an iterable object. When using the list() method, it converts any such object to a list by iterating over it. Example:

>>> list( (1,2,3,4,5) )
[1, 2, 3, 4, 5]
>>> list( 'Hi my name is bob' )
['H', 'i', ' ', 'm', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' ', 'b', 'o', 'b']
>>> [ 'Hi my name is bob' ]
['Hi my name is bob']
>>>

Just use the square brackets instead of list() and you should be good to go.

jlm699 320 Veteran Poster

Ah ha! That worked! Now, since you're putting it in a list to sort the values, is there also a way to separate those values you are sorting on into a list by themselves?

Is this what you mean?

>>> my_dict = {'a':1, 'b':2, 'c':3}
>>> my_dict.keys()
['a', 'c', 'b']
>>> my_dict.values()
[1, 3, 2]
>>>
jlm699 320 Veteran Poster

Can you help?

Why, yes! This case would be a good one to use the dictionary's get method, which will allow you to determine if the key is already in the dictionary or not, and act accordingly.

def file_to_dict(fname):
    f = open("file.txt")
    d = {}
    for line in f:
        columns = line.split(" ")
        letters = columns[0]
        numbers = columns[1].strip()
        if d.get(letters):
            d[letters].append(numbers)
        else:
            d[letters] = list(numbers)
    print d
    
if __name__ == "__main__":
    fname = "file.txt"

Try that on for size.

Basically, by default get will return None if the key is not in the dictionary (you can pass a second parameter to mean default but I prefer None type). So first we check to see if the key is in the dictionary already. If it is, we use the list method append to add the new number onto the end of our list. If the get statement returned None, we instead do what you used to do (create a list as the value to the key).

HTH

jlm699 320 Veteran Poster

Anyone know how to take the readlines() blob and split it up into an array?

The function readlines() already gives you an "array" (it's list in Python). So I guess that part's solved

Welcome to the forum Linky. Please, in the future use code tags (or any other appropriate tag) when you're posting in the forums. It helps us all read your posts better and therefore we're able to give you more solid help and quicker!

This will give you pretty output like this (this is your code reposted w/ tags):

def parseline(input,start,stop):
    for line in input.readlines(): 
        if ":" in line:
            line = line[start:stop]
            print line

--
Now on to your problem: if you're looking to store those numbers instead of merely print them you can just start with an empty list at the beginning of your function, and then append each value to it, which you can then pass back to the calling code:

def parseline(input,start,stop):
    my_numbers = []
    for line in input.readlines(): 
        if ":" in line:
            line = line[start:stop]
            my_numbers.append(float(line))
    return my_numbers

Then in your code when you call parseline(x,y,z) simply use something like numbers = parseline(x,y,z) instead. Then all you need to do is use numbers.sort()

EDIT: Also note that in your function I converted the number to a floating point with float()

EDIT 2: It's pretty common practice in Python to use 4 spaces instead of a tab. Most editors can be set to use a 4 space tabstop …

jlm699 320 Veteran Poster

Could someone explain how this works?

If I'm not mistaken \b means "backspace". So in this example you're writing a seven digit numeral to the screen with %07d and then seven "backspaces" to clear those numerals before writing the next number.

jlm699 320 Veteran Poster

You can stop using IDLE and just run your code in the console, which retains the usage of Ctrl+C (I believe that IDLE tries to catch Ctrl+C)

jlm699 320 Veteran Poster

Here's an indexing example:

>>> mydata = [0.0] * 5
>>> mydata
[0.0, 0.0, 0.0, 0.0, 0.0]
>>> mydata[2] = 45
>>> mydata
[0.0, 0.0, 45, 0.0, 0.0]
>>> mydata[0] = 1.0
>>> mydata
[1.0, 0.0, 45, 0.0, 0.0]
>>> mydata[2]
45
>>>
jlm699 320 Veteran Poster

Actually, the first parameter in the brackets is the index i want to store the value at.

ST=[0.0]
    ST.insert(2,2.2)
    ST.insert(0,0.0)
    ST.insert(3,3.3)
    ST.insert(4,4.4)
    ST.insert(1,1.1)
    ST.insert(5,5.5)
    print ("test point")
    print("my test val 1= ",ST.pop(1))
    print("my test val 2= ",ST.pop(2))
    print("my test val 3= ",ST.pop(3))
    print("my test val 4= ",ST.pop(4))
    print("my test val 5= ",ST.pop(5))

so this should print
my test val 0= 0.0
my test val 1= 1.1
my test val 2= 2.2
my test val 3= 3.3
my test val 4= 4.4
my test val 5= 5.5

Yes, but when you're inserting to an index, that index must exist. Index 2 does not exist in a single element list (only index 0 and index 1). When you insert, you're also extending your list by one. What you want is to declare a list with 0.0 of the desired length as I demonstrated earlier and instead of insert you should be using indexing.

EDIT: Also note that using pop removes that element from the list. Once again, you should be using indexing.

jlm699 320 Veteran Poster

mydata.append((45, 2)) maybe working (doesn't give bugs) but i don't know to check if its gone to where it should since i don't have an extraction method

Why don't you just fire up your interpreter and see what's happening:

>>> mydata = [0.0]
>>> mydata
[0.0]
>>> # mydata only has one element
>>> mydata = [0.0] * 5
>>> mydata
[0.0, 0.0, 0.0, 0.0, 0.0]
>>> # Now mydata has 5 elements
>>> mydata.append((45,2))
>>> mydata
[0.0, 0.0, 0.0, 0.0, 0.0, (45, 2)]
>>> # Using append places the object on the end of the list (this object is a tuple
>>> mydata.insert(2, 45)
>>> mydata
[0.0, 0.0, 45, 0.0, 0.0, 0.0, (45, 2)]
>>> # Using insert (notice index first) "inserts" the object (45) to position 2; however it pushes the rest of the elements up a notch
>>> mydata[4] = 24.2
>>> mydata
[0.0, 0.0, 45, 0.0, 24.199999999999999, 0.0, (45, 2)]
>>> # Looks like indexing is what you should be using.  This changes the element at index 4
>>>

I hope that was clear enough. If not let me know

jlm699 320 Veteran Poster

Is it possible to keep writing the output of a program on the same line instead of moving to a new line every time? The output should be written over the preceding output. An example would be a kind of counter...
say a number that counts from 1 to 10 ...
The normal output of a while loop would be
1
2
3
4
5
etc..

What I want is something that will display 1.. erase it and then display 2.. erase that and display 3 and so on..

To overwrite the previous output you could use the system command os.system('cls') on Windows or os.system('clear') on Linux.

But if you're looking for single character control you'll need to look into curses, which isn't readily available for Windows.

To print on the same line you can end your print statement with a ',' so that instead of printing a new line it prints a space... But that won't help you to clear the previous value