Use enumerate()
like so:
def draw_menu(options, selected_index): for counter, option in enumerate(options): if counter == selected_index: print " [*] %s" % option else: print " [ ] %s" % option options = ['Option 0', 'Option 1', 'Option 2', 'Option 3'] draw_menu(options, 2)
Note: You can optionally put parenthesis around counter, option
, like (counter, option)
, if you want, but they’re extraneous and not normally included.
Related Posts:
- Pythonic way to combine FOR loop and IF statement
- Infinite for loops possible in Python?
- Python – TypeError: ‘int’ object is not iterable
- Why there is no do while loop in python
- Python – TypeError: ‘int’ object is not iterable
- Accessing the index in ‘for’ loops?
- How to avoid “RuntimeError: dictionary changed size during iteration” error?
- How to avoid “RuntimeError: dictionary changed size during iteration” error?
- TypeError: ‘float’ object not iterable
- TypeError: ‘list’ object cannot be interpreted as an integer
- ValueError: max() arg is an empty sequence
- python – if not in list
- Subplot for seaborn boxplot
- Exit while loop in Python
- Pythonic way to iterate through a range starting at 1
- How to iterate through two lists in parallel?
- Loop backwards using indices in Python?
- For loop and ‘numpy.float64’ object is not iterable error
- Why does using from __future__ import print_function breaks Python2-style print?
- Breaking out of nested loops
- Is there a “do … until” in Python?
- What does the “x for x in” syntax mean?
- Iterating over a 2 dimensional python list [duplicate]
- Python: ValueError: Mixing iteration and read methods would lose data
- python: restarting a loop
- “for loop” with two variables?
- How to fix ‘RuntimeWarning: divide by zero encountered in double_scalars’
- List append() in for loop
- Get a Try statement to loop around until correct value obtained
- “for loop” with two variables?
- Write a program that asks the user to enter five test scores. Correspond it to a letter grade
- Python: Continuing to next iteration in outer loop
- are there dictionaries in javascript like python?
- How do I update\upgrade pip itself from inside my virtual environment?
- What does the “yield” keyword do?
- Renaming column names in Pandas
- Does Python have a string ‘contains’ substring method?
- Is there a “not equal” operator in Python?
- IndexError: list index out of range and python
- Python: ‘ModuleNotFoundError’ when trying to import module from imported package
- Check if a given key already exists in a dictionary
- `from … import` vs `import .` [duplicate]
- How to read a text file into a string variable and strip newlines?
- ln (Natural Log) in Python
- How do I select rows from a DataFrame based on column values?
- How to round to 2 decimals with Python?
- How do I concatenate two lists in Python?
- How do I get the row count of a Pandas DataFrame?
- python : comma in print as “\t”
- How can I randomly select an item from a list?
- Python Error: AttributeError: __enter__ [duplicate]
- Get a list from Pandas DataFrame column headers
- ‘End of statement expected’ in pycharm
- How to import files in python using sys.path.append?
- Tensorflow: why ‘pip uninstall tensorflow’ cannot find tensorflow
- TypeError: object of type ‘int’ has no len() – Python/Pygame
- Python: Open file in zip without temporarily extracting it
- Installing tensorflow with anaconda in windows
- Plotting multiple different plots in one figure using Seaborn
- What does “unsqueeze” do in Pytorch?
- Delete an element from a dictionary
- How to iterate over columns of pandas dataframe to run regression
- JSON to pandas DataFrame
- Convert decimal to binary in python
- How to remove specific elements in a numpy array
- Converting between datetime and Pandas Timestamp objects
- Traverse a list in reverse order in Python
- Overflow / math range error for log or exp
- Creating a Pandas DataFrame from a Numpy array: How do I specify the index column and column headers?
- Overflow Error in Python’s numpy.exp function
- Python can’t find module in the same folder
- Can’t connect to local MySQL server through socket ‘/tmp/mysql.sock
- Pandas long to wide reshape, by two variables
- how to create a list of lists
- Python – ‘ascii’ codec can’t decode byte
- Python assigning multiple variables to same value? list behavior
- IDLE’s subprocess didn’t make a connection. Either IDLE can’t start or personal firewall software is blocking the connection
- How to update a plot in matplotlib?
- ImportError: No module named MySQLdb
- Comparing two dictionaries and checking how many (key, value) pairs are equal
- How to fix “AttributeError: module ‘tensorflow’ has no attribute ‘get_default_graph'”?
- Using multiple variables in a for loop in Python
- How do I get the full path of the current file’s directory?
- How to remove project in PyCharm?
- Parse date string and change format
- Appending to a list gives ‘int’ object has no attribute ‘append’
- How do I disable a Pylint warning?
- UDP Client/Server Socket in Python
- How to write an inline-comment in Python
- Unable to resolve ‘requests’. IntelliSense may be missing for this module. Visual Studio/Python
- Python TypeError: ‘set’ object is not subscriptable
- Python and PYAML – yaml.scanner.ScannerError: mapping values are not allowed here
- ValueError: The channel sent is invalid on a Raspberry Pi – Controlling GPIO Pin 2 (BOARD) using Python causes Error
- How can I extract all values from a dictionary in Python?
- Handling a timeout error in python sockets
- Got continuous is not supported error in RandomForestRegressor
- Python 2.7 mixing iteration and read methods would lose data
- Conditional indexing with Numpy ndarray
- python numpy machine epsilon
- Installing lxml module in python