Python Forum
How to change the datatype of list elements? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to change the datatype of list elements? (/thread-38029.html)



How to change the datatype of list elements? - mHosseinDS86 - Aug-23-2022

hi there everyone!
I have a question related to changing the datatype of list:
- How to change the datatype of list?


RE: How to change the datatype of list elements? - Gribouillis - Aug-23-2022

It is very difficult to understand what you want to do and why you want to do it. Can you explain it with more details?


RE: How to change the datatype of list elements? - deanhystad - Aug-23-2022

lists don't have a datatype. Are you thinking arrays? np.arrays and ctypes arrays have types. Python lists can contain objects of different types.


RE: How to change the datatype of list elements? - Yoriz - Aug-23-2022

It might be clearer if you give an example of what the list looked like initially and then how the list should look afterwards.


RE: How to change the datatype of list elements? - mHosseinDS86 - Aug-23-2022

example:
>>>> marks=["50","60","70","80","90"]
all the elements are in string datatype. I want to change elements into integers.


RE: How to change the datatype of list elements? - Yoriz - Aug-23-2022

You can loop through the list and make a new list that changes each item into an int.
marks = ["50", "60", "70", "80", "90"]

marks = [int(mark) for mark in marks]
print(marks)
Output:
[50, 60, 70, 80, 90]



RE: How to change the datatype of list elements? - perfringo - Aug-23-2022

Alternative way is to use built-in map function:

>>> marks = ["50", "60", "70", "80", "90"]
>>> list(map(int, marks))
[50, 60, 70, 80, 90]



RE: How to change the datatype of list elements? - deanhystad - Aug-23-2022

Why would "marks" be strings when you want them to be int? Should the change be upstream?

If you do have a list of str and you want to convert it to a list of int, you might need check for errors. Depending on what action you need to take when converting the str to an int raises a Value error, map() and list comprehensions might not be an option. You may have no other option than looping through the values.
mport numpy as np

marks = ["50", "60.25", "70.75", "spam", "9.25E2"]

for index, mark in enumerate(marks):
    try:
        value = int(mark)
    except ValueError:
        # Cannot convert mark from str to int.  Try converting
        # to float and rounding.
        try:
            value = round(float(mark))
        except ValueError:
            # mark cannot be converted to a number
            value = np.NaN
    marks[index] = value

print(marks)
Output:
[50, 60, 71, nan, 925]
The code converts everything it can to an int, but this would be the wrong place to do the conversion. The correct place to do the conversion is where the data is received. If "marks" is entered using input(), the input strings should be immediately converted to int. If the conversion fails, the user should be prompted to enter correct values.

If the input is received from another system (web scraping, database query, API call), the conversion should happen immediately, and invalid data reported (logging, error trace). It is a lot easier to track down errors if they are reported when they occur instead of when they cause the program to crash.


RE: How to change the datatype of list elements? - mHosseinDS86 - Aug-24-2022

(Aug-23-2022, 05:05 PM)deanhystad Wrote: Why would "marks" be strings when you want them to be int? Should the change be upstream?

If you do have a list of str and you want to convert it to a list of int, you might need check for errors. Depending on what action you need to take when converting the str to an int raises a Value error, map() and list comprehensions might not be an option. You may have no other option than looping through the values.
mport numpy as np

marks = ["50", "60.25", "70.75", "spam", "9.25E2"]

for index, mark in enumerate(marks):
    try:
        value = int(mark)
    except ValueError:
        # Cannot convert mark from str to int.  Try converting
        # to float and rounding.
        try:
            value = round(float(mark))
        except ValueError:
            # mark cannot be converted to a number
            value = np.NaN
    marks[index] = value

print(marks)
Output:
[50, 60, 71, nan, 925]
The code converts everything it can to an int, but this would be the wrong place to do the conversion. The correct place to do the conversion is where the data is received. If "marks" is entered using input(), the input strings should be immediately converted to int. If the conversion fails, the user should be prompted to enter correct values.

If the input is received from another system (web scraping, database query, API call), the conversion should happen immediately, and invalid data reported (logging, error trace). It is a lot easier to track down errors if they are reported when they occur instead of when they cause the program to crash.

I'm sorry, I forgot to mention that I used the input() funtion


RE: How to change the datatype of list elements? - deanhystad - Aug-24-2022

When using input(), the conversion should happen as soon as the value is entered. Something like this:
def enter_mark(prompt="Enter mark: ", min_=0, max_=100):
    while True:
        try:
            entry = input(prompt)
            value = int(entry)
        except ValueError:
            print(f"{entry} is not an integer value")
        else:
            if value < min_ or value > max_:
                print(f"{value} is not in the range {min_}..{max_}")
            else:
                break
    return value

print([enter_mark() for _ in range(5)])