I am new in python. I have a list like this:
new_list = []
list1 = ['a','b','c']
I want to run loop and append item in my new_list by matching len
of list1.
so my expected result will be somethings like this:
new_list = [1,2,3]
if my list1 = ['a','b']
then new_list = [1,2]
CodePudding user response:
Using range()
and casting to a list
:
>>> list1 = ['a','b','c']
>>> new_list = list(range(1, len(list1) 1))
>>> new_list
[1, 2, 3]
CodePudding user response:
thats how you can do it.
for x in range(1,len(list1) 1):
new_list.append(x)
print(new_list)
CodePudding user response:
Using Python's list comprehension, you are able to do this with 2 lines of code.
list1 = ['a','b','c']
new_list = [i for i in range(1, len(list1) 1)]
CodePudding user response:
Another option is to use enumerate
:
list1 = ['a','b','c']
output = [i for i, _ in enumerate(list1, start=1)]
print(output) # [1, 2, 3]