-3

I have a list with the following entries. How can I remove the single quotes for each entries in the list? I need to find the minimum value in the list. When I used min function, result is wrong due to the single quotes in the list. I know the workaround will be, making a script to save the minimum at each loop. But is there any other way to remove the single quotes, which makes the process simpler?

['-406', '-140', '-141', '-66.', '-135', '-142', '-136','-0.01']

The below list is derived from a text file having lot of strings and after using split only Iam getting the single quotes. Can I do something there to avoid the single quotes?

Thanks

Ajith MS
  • 1
  • 3
  • You read the text file in as strings, Python is not going to automatically convert it to numbers even if your text file is all numbers. You have to convert the strings in the list to numbers, or provide the [`key` argument to `min`](https://docs.python.org/3/library/functions.html#min) and have the `keyfunc` convert elements. – wkl Aug 21 '22 at 21:43
  • 1
    Welcome to Stack Overflow. Please make sure you understand the concept of *type*. You cannot "remove" the single quotes because they aren't actually part of the data; they are a part of the **representation of** the data. It is like if you counted six things and wanted to remove the "x" from the "six". – Karl Knechtel Aug 21 '22 at 21:48

2 Answers2

0

You have an array of strings. You can use float or other variants to convert a string to numeric. And then you can call min function on the numeric list.

a= ['-406', '-140', '-141', '-66.', '-135', '-142', '-136','-0.01']

b = [float(i) for i in a]

# gives b as
[-406.0, -140.0, -141.0, -66.0, -135.0, -142.0, -136.0, -0.01]

c = min(b)
# c is
-406.0
Farshid
  • 446
  • 2
  • 9
0

The result is wrong because the values are strings, not because of the single quotes - those are just there in your output to signify that they're strings and lists.

You can convert the values to floats using float, and then use min on the result:

lowest_value = min(map(float, your_list))

map applies the float conversion to every element in the list, then min retrieves the lowest value from the returned iterator.

MatsLindh
  • 49,529
  • 4
  • 53
  • 84