man zet
man zet

Reputation: 901

simple change of lists in python: efficient way?

if i have a list in python were i have a lot of numers example:

list = [1,2,3,12,4,5,23,5,6,56,8,57,8678,345,234,13, .....]

so a list of all integers, that all can have different values ... (i my case this list could be very long, and is actually not an integer list, but a list of Objects which are all from the same type an have a attribute age which is a integer) whats the most efficient way to add all those values by +1 is it

new_list = [x+1 for x in list]

or maybe

new_list = []
for x in list:
    new_list.append(x+1)

(i guess it makes no difference)

or is there maby a more efficent way or an other data sructure to make this more performant? I really wonder if there is not any method, maybe using something different the a list were i can do this operation more efficient because the +1 seems son simple ...

Upvotes: 1

Views: 85

Answers (3)

Mathias Schmid
Mathias Schmid

Reputation: 26

There is no fastest way but I think this is an interesting attempt since u never use more RAM than actually needed (u delete the entries once you copied them)

list1 = []
while (len(list) != 0):
    list1.append(list.pop(0)+1)

After receiving a comment I did some testing and found the results very interesting!

Testing results.

Upvotes: 0

chepner
chepner

Reputation: 531055

If you actually have a list of objects with an integer attribute, as you say, you can update the attribute in-place:

class A(object):
    def __init__(self, x):
        self.x = x

my_list = [A(2), A(5), A(1)]
for obj in my_list:
    obj.x += 1
assert my_list[0].x == 3
assert my_list[1].x == 6
assert my_list[2].x == 2

Upvotes: 3

tengreencolors
tengreencolors

Reputation: 39

Try to use map. It must be fast due to some built-in optimizations.

t = [1, 2, 3, 4, 5, 6, 7, 8]
print (map(lambda x:x + 1, t))

Upvotes: -1

Related Questions