2

I want to avoid doing ugly int to each element in a list.

dictionary[l[0]] = [(int(l[1])+ int(l[2])+ int(l[3]))/3] #avg score of 3 grades
    sub1 += int(l[1])
    sub2 += int(l[2])
    sub3 += int(l[3])

The list l has 4 elements, 0 to 3 indexes. I need to apply int starting with the 1st-element, not 0th element.

I'm trying to write something like:

   map lambda x: int(x) for i in l[1:]

Do I need lambda here, since map can already do the job?

1
  • 1
    You should use float instead of int for computing the average (at least in Python 2) Commented Nov 30, 2018 at 7:38

1 Answer 1

4

map calls a function on each element of a list. Since int is a function you can use

map(int, lst)

directly.

Lambda functions just give you more flexibility, say if you wanted to do:

map(lambda x: 5*int(x), lst)

A more Pythonic way to do the above would be to use list comprehensions

[int(x) for x in lst]
[5*int(x) for x in lst]

In Python3 map returns a generator. If you wish to have a list, you'd want to do:

list(map(int, lst))
Sign up to request clarification or add additional context in comments.

5 Comments

does map return smth? Do I need to do lst = map(int, lst)?
@ERJAN map() returns a map object. You need to convert it into a list. For example: list2 = list(map(int, list1))
IMHO int is better characterized as a callable, not a function.
Thanks, @VPfB, that might well be right. What is a callable and how does it differ from a function?
@Richard Callable is a general term for classes, class methods, functions, lambdas and possibly other objects that can be called docs.python.org/3/reference/expressions.html#calls . Functions are defined with def keyword.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.