1

Is there any way in python where the elements of the list don't get changed.

For eg, integers must remain integers and string must remain string, but this should be done in same program.

The sample code would be:

print("Enter the size of the list:")
N = int(input())
for x in range(N):
    x = input("")    
    the_list.append(x)
    the_list.sort()

print(the_list)

Result: the_list = ['1','2','3']

is the list of integers where integers have converted to strings which is wrong.

But strings of list must remain strings.

8
  • "Being generated"? - what's generating the list? And nothing automatically converts integers into strings. I'm afraid I don't understand your problem. Could you post some sample code and point out how it's not doing what you'd like it to do? Commented Sep 23, 2012 at 7:22
  • @vamosrafa.. Well it could not have converted automatically, unless you explicitly gave integers in string form. Commented Sep 23, 2012 at 7:32
  • Your edit hasn't made it much clearer. Please show the code that generated mylist_int. Commented Sep 23, 2012 at 7:33
  • @vamosrafa.. You need to clarify more clearly.. Add some more code you have written.. Or or problem statemtn will help.. Commented Sep 23, 2012 at 7:39
  • There you go.. See Tim's answer below.. You will get what you want.. Commented Sep 23, 2012 at 7:42

1 Answer 1

3
for x in range(N):
    x = input("")
    try:  
        the_list.append(int(x))
    except ValueError:
        the_list.append(x)

Let's run this:

1
hello
4.5
3
boo
>>> the_list
[1, 'hello', '4.5', 3, 'boo']

Note that you can't sort the list in a meaningful way (Python 2) or at all (Python 3) if it contains mixed types:

>>> sorted([1, "2", 3])                     # Python 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() < int()

>>> sorted([1, "2", 3])                     # Python 2
[1, 3, '2']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.