-4

In python I have lists with sequential names, (list1, list2, list3, list4, etc.) and an integer variable n.

I want to print the second value of a list depending on n. If n == 3 then print the second value of list3.

Red
  • 26,798
  • 7
  • 36
  • 58
stocton12
  • 15
  • 4

2 Answers2

0

Here you have an basic example:


names = [
    ["john", "smith", "jovi"],
    ["tom", "alexander", "hanks"],
    ["mariah", "carey", "vincent"],
]

def print_second_name(names_lists, n):
     second_item_idx = 1
     # index minus 1 as you want to start from 1 instead of cero
     print(names_lists[n - 1][second_item_idx])


print_second_name(names, 2)
# alexander

print_second_name(names, 4)
# IndexError: index out of bounds
BSP
  • 735
  • 1
  • 10
  • 27
0

Maybe you can try a list of lists. If I get what you are going for,

L = [[1,2,3],[2,3],[5,6,7]] #Something like this
n = int(input("Enter a number"))
print("The value is: ", L[n-1][n-2]) #The reason why we use n-1 instead of n in because lists start with 0 index

or something like this