![]() l *= n - updates l with its contents repeated n times.l.extend(t) or l += t - extends l with the contents of t.l.copy() - creates a shallow copy of l (same as l).l.clear() - removes all items from l (same as del l).l.append(x) - appends x to the end of the sequence.del l - removes the elements of s from the list.l = t - the elements of l are replaced by those of t.l = t - slice of l from i to j is replaced by the contents of the iterable t.l.index(x]) - index of the 1st occurrence of x in l (at or after i and before j indeces)Ī list also implements all of the mutable sequence operations:.Detailed Explanation ListĪ list is a mutable sequence, typically used to store collections of homogeneous items.Ī list implements all of the common sequence operations: ![]() Set - if you require to keep unique elements. ![]() List - if you require an ordered sequence of items.ĭict - if you require to relate values with keys So, if you have hashable items, don't care either way about order or duplicates, and want speedy membership checking, set is better than list. (A "multiset", which maps duplicates into a different count for items present more than once, can be found in collections.Counter - you could build one as a dict, if for some weird reason you couldn't import collections, or, in pre-2.7 Python as a faultdict(int), using the items as keys and the associated value as the count).Ĭhecking for membership of a value in a set (or dict, for keys) is blazingly fast (taking about a constant, short time), while in a list it takes time proportional to the list's length in the average and worst cases. Set forbids duplicates, list does not: also a crucial distinction. Set requires items to be hashable, list doesn't: if you have non-hashable items, therefore, you cannot use set and must instead use list. A list keeps order, dict and set don't: when you care about order, therefore, you must use list (if your choice of containers is limited to these three, of course -) ).ĭict associates each key with a value, while list and set just contain values: very different use cases, obviously.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |