Python Forum
How to change the datatype of list elements?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to change the datatype of list elements?
#1
hi there everyone!
I have a question related to changing the datatype of list:
- How to change the datatype of list?
Reply
#2
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?
Reply
#3
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.
Reply
#4
It might be clearer if you give an example of what the list looked like initially and then how the list should look afterwards.
Reply
#5
example:
>>>> marks=["50","60","70","80","90"]
all the elements are in string datatype. I want to change elements into integers.
Yoriz write Aug-23-2022, 03:26 PM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#6
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]
mHosseinDS86 and ndc85430 like this post
Reply
#7
Alternative way is to use built-in map function:

>>> marks = ["50", "60", "70", "80", "90"]
>>> list(map(int, marks))
[50, 60, 70, 80, 90]
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#8
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.
Reply
#9
(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
Reply
#10
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)])
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  unable to remove all elements from list based on a condition sg_python 3 429 Jan-27-2024, 04:03 PM
Last Post: deanhystad
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 470 Oct-17-2023, 09:46 AM
Last Post: tomciodev
  Change font in a list or tuple apffal 4 2,670 Jun-16-2023, 02:55 AM
Last Post: schriftartenio
  Checking if a string contains all or any elements of a list k1llcod3 1 1,095 Jan-29-2023, 04:34 AM
Last Post: deanhystad
  find some word in text list file and a bit change to them RolanRoll 3 1,522 Jun-27-2022, 01:36 AM
Last Post: RolanRoll
  ValueError: Length mismatch: Expected axis has 8 elements, new values have 1 elements ilknurg 1 5,116 May-17-2022, 11:38 AM
Last Post: Larz60+
Question Change elements of array based on position of input data Cola_Reb 6 2,113 May-13-2022, 12:57 PM
Last Post: Cola_Reb
  datatype check arkiboys 1 1,175 Jan-18-2022, 12:46 PM
Last Post: ndc85430
  Change a list to integer so I can use IF statement buckssg 3 2,234 Sep-21-2021, 02:58 AM
Last Post: bowlofred
  change csv file into adjency list ainisyarifaah 0 1,502 Sep-21-2021, 02:49 AM
Last Post: ainisyarifaah

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020