1

What is the best way to add values to a List in terms of processing time, memory usage and just generally what is the best programming option.

list = []

for i in anotherArray:
    list.append(i)

or

list = range(len(anotherArray))

for i in list:
    list[i] = anotherArray[i]

Considering that anotherArray is for example an array of Tuples. (This is just a simple example)

1

3 Answers 3

1

It really depends on your use case. There is no generic answer here as it depends on what you are trying to do.

In your example, it looks like you are just trying to create a copy of the array, in which case the best way to do this would be to use copy:

from copy import copy    
list = copy(anotherArray)

If you are trying to transform the array into another array you should use list comprehension.

list =  [i[0] for i in anotherArray]  # get the first item from tuples in anotherArray

If you are trying to use both indexes and objects, you should use enumerate:

for i, j in enumerate(list)

which is much better than your second example.

You can also use generators, lambas, maps, filters, etc. The reason all of these possibilities exist is because they are all "better" for different reasons. The writters of python are pretty big on "one right way", so trust me, if there was one generic way which was always better, that is the only way that would exist in python.


Edit: Ran some results of performance for tuple swap and here are the results:

comprehension: 2.682028295999771
enumerate: 5.359116118001111
for in append: 4.177091988000029
for in indexes: 4.612594166001145

As you can tell, comprehension is usually the best bet. Using enumerate is expensive. Here is the code for the above test:

from timeit import timeit

some_array = [(i, 'a', True) for i in range(0,100000)]

def use_comprehension():
    return [(b, a, i) for i, a, b in some_array]

def use_enumerate():
    lst = []
    for j, k in enumerate(some_array):
        i, a, b = k
        lst.append((b, a, i))
    return lst

def use_for_in_with_append():
    lst = []
    for i in some_array:
        i, a, b = i
        lst.append((b, a, i))
    return lst

def use_for_in_with_indexes():
    lst = [None] * len(some_array)
    for j in range(len(some_array)):
        i, a, b = some_array[j]
        lst[j] = (b, a, i)
    return lst

print('comprehension:', timeit(use_comprehension, number=200))
print('enumerate:', timeit(use_enumerate, number=200))
print('for in append:', timeit(use_for_in_with_append, number=200))
print('for in indexes:', timeit(use_for_in_with_indexes, number=200))

Edit2:

It was pointed out to me the the OP just wanted to know the difference between "indexing" and "appending". Really, those are used for two different use cases as well. Indexing is for replacing objects, whereas appending is for adding. However, in a case where the list starts empty, appending will always be better because the indexing has the overhead of creating the list initially. You can see from the results above that indexing is slightly slower, mostly because you have to create the first list.

Sign up to request clarification or add additional context in comments.

5 Comments

I already mentioned enumeration which is definitely the best for contained operations.
@Malik I diasagree, list comprehensions are more performant and more pythonic for most cases.
That was such a bad example by me with the copy... I don't think anyone here is understanding the question... It's in the title really. I ask "Indexing or Appending", not "What is the best type of for"... But thanks anyway, it's helpful to know what is best in each situation.
@Rayden your comment actually helps me understand the question. Ill update the answer here in a little.
@Nick Thanks thats exactly what i wanted. I thought that append would take more time because of the experience I had with numpy arrays, but I just researched and people say that they work in a different way than lists, so for lists its better to use append or if i don't have a lot of operations to do, I will use list comprehension.
1

Best way is list comprehension :

my_list=[i for i in anotherArray]

But based on your problem you can use a generator expression (is more efficient than list comprehension when you just want to loop over your items and you don't need to use some list methods like indexing or len or ... )

my_list=(i for i in anotherArray)

6 Comments

Yes but I'm concerned when I'm doing operations in each iteration, that's just for a simple copy. I should have explained myself better.
@Rayden What you mean by operation? when you can access to each item in iteration you can do any operation on it!
@Rayden Do you mean an in-place operation?
I mean like using ifs and elses (i know that you can in list comprehension but it's much more limited), doing calculations etc.
@Rayden In that case it could have a lot of scenarios! its all depend on your problem! because you can use a lot of python's tools for making your code more efficient and quicker!
|
0

I would actually say the best is a combination of index loops and value loops with enumeration:

for i, j in enumerate(list): # i is the index, j is the value, can't go wrong

4 Comments

Thus you can use one or the other when needed.
Right, I've been researching that and I think it's useful but I don't think anyone here is understanding the question... It's in the title really. I ask "Indexing or Appending", not "What is the best type of for"...
Doesn't append take more time tho? In a way that when you keep changing the list size you have to go get the desired memory everytime. When you have a fixed size its always constant and you only have to worry about changing the values inside.
They are two really different operations. Append adds an item to the end. Indexing changes the value at a given point. One's not better than the other, they are completely different operations.

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.