list extend() to index, inserting list elements not only to the end

Sure, you can use slice indexing: a_list[1:1] = b_list Just to demonstrate the general algorithm, if you were to implement the my_extend function in a hypothetical custom list class, it would look like this: def my_extend(self, other_list, index): self[index:index] = other_list But don’t actually make that a function, just use the slice notation when you … Read more

My async call is returning before list is populated in forEach loop

This code Future<List<String>> readHeaderData() async { List<String> l = new List(); List<String> files = await readHeaders(); // Gets filenames files.forEach((filename) async { final file = await File(filename); String contents = await file.readAsString(); User user = User.fromJson(json.decode(contents)); String name = user.NameLast + “, ” + user.NameFirst; print(name); l.add(name); } return l; } returns the list l … Read more

Comparing 2 lists consisting of dictionaries with unique keys in python

Assuming that the dicts line up like in your example input, you can use the zip() function to get a list of associated pairs of dicts, then you can use any() to check if there is a difference: >>> list_1 = [{‘unique_id’:’001′, ‘key1′:’AAA’, ‘key2′:’BBB’, ‘key3′:’EEE’}, {‘unique_id’:’002′, ‘key1′:’AAA’, ‘key2′:’CCC’, ‘key3′:’FFF’}] >>> list_2 = [{‘unique_id’:’001′, ‘key1′:’AAA’, ‘key2′:’DDD’, … Read more

deque.popleft() and list.pop(0). Is there performance difference?

deque.popleft() is faster than list.pop(0), because the deque has been optimized to do popleft() approximately in O(1), while list.pop(0) takes O(n) (see deque objects). Comments and code in _collectionsmodule.c for deque and listobject.c for list provide implementation insights to explain the performance differences. Namely that a deque object “is composed of a doubly-linked list”, which … Read more

Python: Random numbers into a list

You could use random.sample to generate the list with one call: import random my_randoms = random.sample(range(100), 10) That generates numbers in the (inclusive) range from 0 to 99. If you want 1 to 100, you could use this (thanks to @martineau for pointing out my convoluted solution): my_randoms = random.sample(range(1, 101), 10)

Performance and Memory allocation comparison between List and Set

HashSet consumes about 5.5 times more memory than ArrayList for the same number of elements (although they’re both still linear), and has significantly slower iteration (albeit with the same asymptotics); a quick Google search suggests a 2-3x slowdown for HashSet iteration versus ArrayList. If you don’t care about uniqueness or the performance of contains, then … Read more