11
[112L, 114L, 115L, 116L, 117L, 118L, 119L, 120L, 121L, 122L, 123L, 124L, 125L, 126L] 

How can I convert this list into a list of integer values of those mentioned values? I tried int() but it returned an error. Any idea guys?

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
vellattukudy
  • 789
  • 2
  • 11
  • 25
  • 1
    What code gave you the error? What error was it? Please provide enough details for people to help you. – BallpointBen Nov 04 '15 at 10:41
  • what error returned? – Hasan Ramezani Nov 04 '15 at 10:41
  • Possible duplicate of [How can I check if a string has a numeric value in it in Python?](http://stackoverflow.com/questions/12466061/how-can-i-check-if-a-string-has-a-numeric-value-in-it-in-python) – Bonatti Nov 04 '15 at 10:52
  • 2
    Why do you want to convert the longs to integers? The list should work the same whether it contains integers or longs. Or are you just doing `print(my_list)`, and don't like the look of the 'L's? – Alasdair Nov 04 '15 at 11:03

3 Answers3

16

You generally have many ways to do this. You can either use a list comprehension to apply the built-in int() function to each individual long element in your list:

l = [112L, 114L, 115L, 116L, 117L, 118L, 119L, 120L, 121L, 122L, 123L, 124L, 125L, 126L]

l2 = [int(v) for v in l]

which will return the new list l2 with the corresponding int values:

[112, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126]

Or, you could use map(), which is another built-in function, in conjunction with int() to accomplish the same exact thing:

# gives similar results
l2 = map(int, l) 
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
5

Use list comprehension and convert each element in the list to an integer. Have a look at the code below:

>>> l = [112L, 114L, 115L, 116L, 117L, 118L, 119L, 120L, 121L, 122L, 123L, 124L, 125L, 126L]
>>> i = [int(a) for a in l]
>>> print i
[112, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126]
JRodDynamite
  • 12,325
  • 5
  • 43
  • 63
5

I would use map-

l = [112L, 114L, 115L, 116L, 117L, 118L, 119L, 120L, 121L, 122L, 123L, 124L, 125L, 126L]
print map(int,l)

Prints-

[112, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126]
Learner
  • 5,192
  • 1
  • 24
  • 36