ksss
ksss

Reputation: 45

Editing the elements of a list in python 3

My question is kind of a two part question.

If you are given a list

numbers = [10, 20, 30, 100]

and you wish to edit every element inside the list by adding 10 to each element. How would I go about doing this? And are you able to do this without creating a separate list?

Similarly, if you are given a list such as:

words = ['hello', 'hey', 'hi'] 

and wish to change every letter h inside the list to another letter say 'r' would it be a similar algorithm as the last?

Upvotes: 2

Views: 305

Answers (2)

user5538922
user5538922

Reputation:

Because you said you don't want to create a new list, you can't use list comprehension or map function as @gcandal suggested. You can try this instead.

def update_list(l, fn):
    for i in range(len(l)):
        l[i] = fn(l[i])

update_list(numbers, lambda a: a + 10)
update_list(words, lambda s: s.replace('h', 'r'))

Upvotes: 3

gcandal
gcandal

Reputation: 957

You can do it by applying map:

numbers_plus_ten = map(lambda number: number + 10, numbers)

Or using list comprehension:

numbers_plus_ten = [number + 10 for number in numbers]

Upvotes: 2

Related Questions