![]() |
|
[Tut] Python List index() - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Python List index() (/thread-94263.html) |
[Tut] Python List index() - xSicKxBot - 03-27-2020 Python List index() This tutorial shows you everything you need to know to help you master the essential Code: index()Definition and Usage: The Code: list.index(value)Code: valueCode: listCode: startCode: stopCode: ValueErrorHere’s a short example: Code: >>> lst = ["Alice", 42, "Bob", 99]
>>> lst.index("Alice")
0
>>> lst.index(99)
3
>>> lst.index(99, 1, 3) Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> lst.index(99, 1, 3)
ValueError: 99 is not in listIn the first line of the example, you create the list Code: lstCode: "Alice"Code: 99Code: start=1Code: stop=3Code: 99Code: ValueErrorCode Puzzle — Try It Yourself: Now you know the basics. Let’s deepen your understanding with a short code puzzle—can you solve it? https://repl.it/@finxter/PythonListIndex?lite=true You can also solve this puzzle and track your Python skills on our interactive Finxter app. Syntax: You can call this method on each list object in Python (Python versions 2.x and 3.x). Here’s the syntax: Code: list.index(value, start=0, stop=9223372036854775807)Arguments: Argument | Description Code: valueReturns the index of Code: valueCode: listCode: ==Code: TrueCode: -1Code: start(Optional.) The index of where you want to start searching in the list. All list elements in front of this position are ignored. This is a positional argument, not a keyword argument. Code: stop(Optional.) The index of where you want to stop searching in the list. All list elements after this position are ignored. This is a positional argument, not a keyword argument. Return value: The method Code: list.index(value)Code: valueCode: ValueErrorRelated article: Python Regex Superpower – The Ultimate Guide Python List Index Implementation Python List Index Time Complexity Python List Index Out of Range Python List Index Without Exception Python List Index Try Catch Python List Index Multiple Python List Index Range Python List Index of Max / Min Python List Index From End (Reverse) Python List Index Regex Python List Index Wildcard Python List Index Enumerate Python List Index Exclude Python List Index Tuple Python List Index True False Python List Index Zero / Non-Zero Python List Index Pop Python List Index Delete Python List Index Slice / Substring Python List Index By Value / Key / Array / Tuple Python List Index Multidimensional Related articles: Python List Count Runtime Complexity The time complexity of the Code: count(value)Again, have a look at the reference implementation where you can see these comparison operations Code: element == valueCode: def count(lst, value): count = 0 for element in lst: count += element == value return countThus, the time complexity is linear in the number of list elements. You can see a plot of the time complexity of the Code: count()![]() The figure shows how the elapsed time of counting a dummy element -99 in lists with growing number of elements grows linear to the number of elements. If you’re interested in the code I used to generate this plot with Matplotlib, this is it: Code: import matplotlib.pyplot as plt
import time y = []
for i in [100000 * j for j in range(10,100)]: lst = list(range(i)) t0 = time.time() x = lst.count(-99) t1 = time.time() y.append(t1-t0) plt.plot(y)
plt.xlabel("List elements (10**5)")
plt.ylabel("Time (sec)")
plt.show()How can you count the number of duplicates in a given list? Problem: Let’s consider an element a duplicate if it appears at least two times in the list. For example, the list Code: [1, 1, 1, 2, 2, 3]Code: 1Code: 2Solution: You create an empty set duplicates. Then you iterate over the original list and add each element to the set that has a count value of at least 2. Here’s the code: Code: def find_dups(lst): dups = set() for el in lst: if lst.count(el)>1: dups.add(el) return dups print(find_dups([1, 1, 1, 2, 2, 3]))
# {1, 2} print(find_dups(["Alice", "Bob", "Alice"]))
# {'Alice'} print(find_dups([1, 2, 3]))
# set()Note that this algorithm has quadratic time complexity because for each element in the list, you need to count the number of times it appears in the list—each of those count operations has linear time complexity. Related article: Python List Count Unique Values and Strings How can you count the number of unique values (or strings) in a given list? Problem: A value is considered unique if it appears only once in the list. Solution: You count each Code: elementCode: list.count(element) == 1Here’s the code: Code: def find_uniques(lst): uniques = set() for el in lst: if lst.count(el) == 1: uniques.add(el) return uniques print(find_uniques([1, 1, 2, 3, 3]))
# {2} print(find_uniques(["Alice", "Bob", "Alice"]))
# {'Bob'}This algorithm has quadratic time complexity because for each element in the list, you need to count the number of times it appears in the list—each of those count operations has linear time complexity. Python List Count All Elements (Count to Dict) How can you count all elements in a list and store the result in a dictionary? Problem: Given is a list. You want to count each element in the list. Then, you want to store the result in a dictionary mapping the elements to their frequencies of appearance (counts). For example, the list Code: [1, 1, 2, 2, 3]Code: {1:2, 2:2, 3:1}Solution: You solve this problem using dictionary comprehension. The key is the list element and the value is the frequency of this element in the list. You use the Code: count()Here’s the code: Code: def count_to_dict(lst): return {k:lst.count(k) for k in lst} print(count_to_dict(["Alice", "Bob", "Ann", "Alice", "Charles"]))
# {'Alice': 2, 'Bob': 1, 'Ann': 1, 'Charles': 1} print(count_to_dict([1, 1, 1, 2, 2, 3]))
# {1: 3, 2: 2, 3: 1}This algorithm has quadratic time complexity because for each element in the list, you need to count the number of times it appears in the list—each of those count operations has linear time complexity. Related article: Python List Count With Condition How can you count elements under a certain condition in Python? For example, what if you want to count all even values in a list? Or all prime numbers? Or all strings that start with a certain character? There are multiple ways to accomplish this, let’s discuss them one by one. Say, you have a condition for each element Code: xCode: condition(x)Code: def condition(x): return x > 10 print(condition(10))
# False print(condition(2))
# False print(condition(11))
# TrueBut you can also define more complicated conditions such as checking if they are prime numbers. Python List Count If How can you count the elements of the list IF the condition is met? The answer is to use a simple generator expression Code: sum(condition(x) for x in lst)Code: >>> def condition(x): return x>10 >>> lst = [10, 11, 42, 1, 2, 3]
>>> sum(condition(x) for x in lst)
2The result indicates that there are two elements that are larger than 10. You used a generator expression that returns an iterator of Booleans. Note that the Boolean Code: TrueCode: FalsePython List Count Greater / Smaller Than If you want to determine the number of elements that are greater than or smaller than a specified value, just modify the condition in this example: Code: >>> def condition(x): return x>10 >>> lst = [10, 11, 42, 1, 2, 3]
>>> sum(condition(x) for x in lst)
2For example, to find the number of elements smaller than 5, use the condition x<5 in the generator expression: Code: >>> lst = [10, 11, 42, 1, 2, 3]
>>> sum(x<5 for x in lst)
3To count the number of zeros in a given list, use the Code: list.count(0)To count the number of non-zeros in a given list, you should use conditional counting as discussed before: Code: def condition(x): return x!=0 lst = [10, 11, 42, 1, 2, 0, 0, 0]
print(sum(condition(x) for x in lst))
# 5An alternative is to use a combination of the map and the lambda function. Related articles:
Here’s the code: Code: >>> sum(map(lambda x: x%2==0, [1, 2, 3, 4, 5]))
2You count the number of even integers in the list.
The result is the number of elements for which the condition evaluates to Code: TruePython List Count Regex / Count Matches Given a list of strings. How can you check how many list elements match a certain regex pattern? (If you need a refresher on Python regular expressions, check out my ultimate guide on this blog– it’s really ultimate!)
Solution: Use the concept of generator expressions with the ternary operator. Related articles: Here’s the code: Code: >>> import re
>>> p = 'a...e'
>>> lst = ['annie', 'alice', 'apex']
>>> sum(1 if re.match(p, x) else 0 for x in lst)
2Do you want to count all string occurrences of a given prefix (e.g. prefix Code: "Sus"Code: "Susie"Code: "Susy"Code: "Susi"Solution: Again you can use the concept of generator expressions with the ternary operator. Related articles: Here’s the code for this one using the wildcard operator in a pattern to count all occurrences of this pattern in the list. Code: >>> import re
>>> lst = ['Susi', 'Ann', 'Susanne', 'Susy']
>>> pattern = 'Sus.*'
>>> frequency = sum(1 if re.match(pattern, x) else 0 for x in lst)
>>> print(frequency)
3The generator expression produces a bunch of 1s and 0s—the former if the list element starts with prefix Code: 'Sus'Python List Count Not Working The Code: list.count(value)Code: >>> lst = [1, 1, 1, 2, 2, 3]
>>> lst.count(1)
3
>>> lst.count(2, 2)
Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> lst.count(2, 2)
TypeError: count() takes exactly one argument (2 given)
>>> lst.count(4)
0
>>> lst.count("1")
0
>>> count(lst)
Traceback (most recent call last): File "<pyshell#22>", line 1, in <module> count(lst)
NameError: name 'count' is not defined
>>>You have to try really hard to break it. Just consider these tips:
Python List Reference Count The Python garbage collector keeps track of the number of times each object in memory is referenced. You call this “reference counting”. All objects that have reference count of zero cannot be reached by your code and, thus, can be safely removed by the garbage collector. It’s unrelated to Python lists with the one exception: each list element increases the reference count by one because a list really is an array of pointers to the list objects in memory in the cPython implementation. Python List Count Tuples How can you count the number of times a given tuple appears in a list? Simply use the tuple as the input argument value for the Code: list.count(value)Code: >>> lst = [(1, 2), (1, 1), 99, "Alice", True, (1, 1)]
>>> lst.count((1, 1))
2How can you count the number of tuples in a given list? Use the Code: type(x)Code: xCode: tupleHere’s an example: Code: >>> sum(type(x)==tuple for x in lst)
3Related articles: Python List Count and Sort Given: list Code: lstProblem: You want to count the number of occurrences of all values in the list and sort them by their frequency. Example: for list elements [1, 1, 1, 1, 0, 0, 3, 1, 1, 3, 3, 3] you want to obtain their frequencies in a sorted manner: Code: 6 times --> element 1
4 times --> element 3
2 times --> element 0Solution: Use the Code: collections.Counter(lst).most_common()Code: import collections lst = [3, 2, 1, 1, 1, 2, 2, 3]
print(collections.Counter(lst).most_common())Generates output: Code: [(2, 3), (1, 3), (3, 2)]Do you want to improve performance of the Code: list.count(value)There’s not much you can do about it. Of course, if you need to count the same element multiple times, you can use a cache dictionary to store its result. But this works only if the list has not changed. You can also sort the list once which takes O(n log n) for n list elements. After that, you can call the implement a count method based on binary search withO(log n) runtime complexity. But if you need to count only a single element, this is not effective. Interestingly, counting all elements in a list also has O(n) runtime complexity. Why? Because you’ll go over each element and add it to a dictionary if it doesn’t exist already (mapping the element to its counter value, initially 1). If it exists, you simply increment the counter by one. In this excellent benchmark, you can find the performance of different counting methods. The Counterclass seems to have best performance. Python List Count vs Len What’s the difference?
Here’s a minimal example: Code: >>> lst = [1, 2, 2, 2, 2]
>>> lst.count(2)
4
>>> len(lst)
5Do you have multiple threads that access your list at the same time? Then you need to be sure that the list operations (such as Code: count()In other words: can you call the Code: count()The answer is yes (if you use the cPythonimplementation). The reason is Python’s global interpreter lock that ensures that a thread that’s currently working on its code will first finish its current basic Python operation as defined by the cPython implementation. Only if it terminates with this operation will the next thread be able to access the computational resource. This is ensured with a sophisticated locking scheme by the cPython implementation. The only thing you need to know is that each basic operation in the cPython implementation is atomic. It’s executed wholly and at once before any other thread has the chance to run on the same virtual engine. Therefore, there are no race conditions. An example of such a race condition would be the following: the first thread reads a value from the list, the second thread overwrites the value, and the first thread overwrites the value again invalidating the second thread’s operation. All cPython operations are thread-safe. But if you combine those operations into higher-level functions, those are not generally thread safe as they consist of many (possibly interleaving) operations. Where to Go From Here? The Code: list.count(x)Code: xCode: listYou’ve learned the ins and outs of this important Python list method. If you keep struggling with those basic Python commands and you feel stuck in your learning progress, I’ve got something for you: Python One-Liners (Amazon Link). In the book, I’ll give you a thorough overview of critical computer science topics such as machine learning, regular expression, data science, NumPy, and Python basics—all in a single line of Python code! Get the book from Amazon! OFFICIAL BOOK DESCRIPTION: Python One-Liners will show readers how to perform useful tasks with one line of Python code. Following a brief Python refresher, the book covers essential advanced topics like slicing, list comprehension, broadcasting, lambda functions, algorithms, regular expressions, neural networks, logistic regression and more. Each of the 50 book sections introduces a problem to solve, walks the reader through the skills necessary to solve that problem, then provides a concise one-liner Python solution with a detailed explanation. |