"List index of range" with list entered by keyboard

0

When I run my Python script, why do I get the error:

  

List index out of range

although the index exists in the list? Here is my code:

a=[input()]
b=input()
c=int(input())

d=[a[0], a[2]]
print(d)

When executing it, this is the error:

Traceback (most recent call last):                                              
  File "lista.py", line 6, in <module>                                          
    d=[a[0], a[2]]                                                              
IndexError: list index out of range  

Then, I modified my code like this:

a=list(input())
b=str(input())
c=int(input())

new_a = [b, a[1], a[2], c]
print(new_a)

When printing, it does not identify the elements of a as a list, so when entering, for example:

carro, silla, mesa
pelota
56

The program gives me the result:

['pelota', 'a', 'r', 56]

I want that in position [1] and [2] of the new list go the [1] and [2] of the previous list, in which failure?

    
asked by Luis Suárez 14.02.2018 в 06:49
source

1 answer

3

On your code, what you enter on line #1 will be registered as a tuple or as a string, that's why the index you're using a[2] does NOT EXIST.

To check it you can print the complete list:

print(a)

In turn you can also use:

print(a[0])

You can check that everything entered by keyboard through input() was saved only in the first element of the list.

You can also use a for to try to scroll through the elements and check the length of the list a according to the number of impressions in console:

for elemento in a:
    print elemento

Edit:

According to your comment:

  

The program that I must do is the following: Create a program in Python 3 that asks the user to enter a list (minimum with one element), a word and a number, then modify the first element of the list with the word entered and add the number to the end of the list. As a result, the program will display the modified list on the screen. The program must show the list exclusively, it must not contain letters or statements that accompany it.

The program would be something like this:

lista = list(input("Ingrese una lista: ").split())  # carro, silla, mesa
palabra = input("Ingrese una palabra: ")            # telefono
numero = int(input("Ingrese un numero: "))          # 372

lista[0] = palabra
lista.append(numero)
print(lista) # Debe imprimir ['telefono', 'silla', 'mesa', 372]

What is found after the # are comments in Python of how you should write them when you enter the data to your program, I enclose a copy of the program's command line output so you can see that it works. / p>

Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux

Ingrese una lista:  casa, auto, telefono
Ingrese una palabra:  celular
Ingrese un numero:  123
['celular', 'auto,', 'telefono', 123]
>>

I hope it serves you.

    
answered by 14.02.2018 / 08:08
source