0

Print each item in the list ["The Walking Dead", "Entourage", "The Sopranos", "The Vampire Diaries"] and its index. Make sure to print its index first. Then, print the movie name.

I am taking a python course in Udemy and this one of the tasks. I keep getting an incorrect output. I believe its because they want the output in a list. This is the code I am inputing, but I am not sure how to get the output in a list.

x = ["The Walking Dead", "Entourage", "the sopranos", "The Vampire Diaries"]
index= 0
for i in x:
    print(index, i)
    index += 1
    
dfundako
  • 8,022
  • 3
  • 18
  • 34
Fernbizz
  • 3
  • 3

3 Answers3

1

To print output in a list, you can use a list comprehension:

x = ["The Walking Dead", "Entourage", "the sopranos", "The Vampire Diaries"]

[i for i in x]

To get the index and the name together in a list, you can also add enumerate

[i for i in enumerate(x)]
dfundako
  • 8,022
  • 3
  • 18
  • 34
0

Use enumerate:

x = ["The Walking Dead", "Entourage", "the sopranos", "The Vampire Diaries"]
for i,name in enumerate(x):
    print(f"{i}\t{name}")

From the documentation:

Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.

blackbrandt
  • 2,010
  • 1
  • 15
  • 32
0

Store a tuple in the return list, let each of it's items contain ( index, name ) and instead of using index var try using range function.

Pawan Nirpal
  • 565
  • 1
  • 12
  • 29