vamosrafa
vamosrafa

Reputation: 695

Python Lists input- Integers and Strings

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.

Upvotes: 1

Views: 13684

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336118

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']

Upvotes: 3

Related Questions