-1

I'm trying to make a simple program to print out a new list made out of the first and last element of a given list.

default_list = [5, 10, 15, 20, 25]
first_list = [7, 233, 76, 234, 2]
second_list = [0, 5, 2, 6, 3423456]
third_list = [768, 56, 234, 765, 2434, 78676, 345, 467, 353, 765343]
new_list = []


def list_ends(chosen_list):
    new_list.append(chosen_list[0])
    new_list.append(chosen_list[len(chosen_list) - 1])
    print(new_list)


list_ends(input(": "))

but what happens is if I enter a word in input say "default_list" it gives me an answer [d, t] which I believe means it didn't call the list variable I created.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Ryuha
  • 3
  • 2

2 Answers2

0

Just for reference, it is possible to read a variable name as an input, like so:

list_name = input("List name: ")
if list_name in locals():
    list_ends(locals()[list_name])
else:
    print('List {} not found'.format(list_name))

However, your use-case does not require such a solution. I'm sure there's a better way to do what you want to do. For e.g., creating a dict mapping string inputs to the lists, then reading the string from input, and using the dictionary to get the corresponding list.

entropy
  • 840
  • 6
  • 16
0

In Python 2, the input function actually allowed you to type in Python expressions, but in Python 3, it simply returns a string, i.e. a sequence of characters.

Just like "list" and list are distinct, the string "default_list" has no direct relation to the variable of the same name.

However, you can bridge this gap:

listname = input("List name: ")
selected = locals()[listname]

Before you plunge ahead with this, you should understand that allowing a user to access the internals of your program is problematic for a number of reasons. Perhaps you should instead offer a menu of numbered choices, for example? That way, a user can't access arbitrary program variables, only the ones you have explicitly made available.

tripleee
  • 175,061
  • 34
  • 275
  • 318