'How can I print a list "nicely" and numbered? [duplicate]
I need to print a list in Python nicely and numbered. For example, if this is my list:
list = ["hello", "dad", "milk"]
this is the output I want:
[1] -hello
[2] -dad
[3] -milk
This is what I have tried:
list = ["hello", "dad", "milk"]
list_element = 0
stuff = len(list)
while stuff != list_element:
element = list[list_element]
print(f"[{list_element}] -{element}")
list_element = list_element + 1
and this is the output I get:
[0] -hello
[1] -dad
[2] -milk
but I don't know how to make it start from 1 (I know in programming you start with 0, but I want to start with 1!)
edit: I forgot to mention this was homework and we didn't learn about the for loop yet so my teacher said I shouldn't use it as to not confuse my classmates lol
Solution 1:[1]
You can simply to it using enumerate in Python, as follows:
list = ["hello", "dad", "milk"]
for i, element in enumerate(list, 1): # to start with index 1, instead of 0
print(f"[{i}] -{element}")
Result:
[1] -hello
[2] -dad
[3] -milk
You can get more informatoin and example about enumerate here:
https://www.programiz.com/python-programming/methods/built-in/enumerate
In additon, one tip is that it is not good to use pre-defined keyword as a variable name such as list.
Solution 2:[2]
You could also use enumerate.
myList = ["hello", "dad", "milk"]
for count, element in enumerate(myList):
print(f"[{count+1}] -{element}")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Park |
| Solution 2 | Supertech |
