0

If i have 2 lists, the first list which has 100 values

listNum = list(range(1, 101))

the second list which has 3 values

cars = ["Ford", "Volvo", "BMW"]

If i would like to add listNum values in next to cars which will be like this

for x in listNum:
    car = cars[x]
    print(cars)

output: Ford1, Volvo2

How can i do that? I know I can make the loop like this,

for x in range(3):

But this is exhausting, i want to add a car without adjusting the loop range, every time I add a car I have to change the loop range

3
  • 2
    for x in range(len(cars)): you can use len of the lists and iterate over it Commented Jun 30, 2021 at 10:55
  • @Sujay But the numbers in the listNum list are not printed next to the cars BMW1 Volvo2 Commented Jun 30, 2021 at 11:02
  • 1
    Then you can use enumerate Commented Jun 30, 2021 at 11:05

2 Answers 2

4

The easiest way to implement this use case is to use enumerate:

for i, car in enumerate(cars, start=1):
    print(f'{car}{i}')
Sign up to request clarification or add additional context in comments.

Comments

1

Your best bet is use for x in range(len(cars)):

The len function takes the number of characters or elements in the specified argument. This way, you won't need to update your loop manually.

for x in range(len(cars)):
    car = cars[x]
    print(car,x)

Here is the best solution

for x,y in enumerate(cars, start=1):
    print(x,y)

2 Comments

This is the output from you 2nd post: 0 Ford 1 Volvo 2 BMW - please verify your outputs with the PO expected outputs.
@DanielHao, enumerate starts from 0 by default

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.