0

Hello I am really new to learning python, and I am getting confused working with lists.

I wrote the following and I get the following

TypeError: list indices must be integers, not str

My code is:

numlist = list()
listy = ['341', '22', '1803']
for i in listy:
    numlist = int(listy[i])

So in this program I am trying to write, part of it includes a list of numbers. I want to take those numbers and append them to another list (numlist) that converts each entry in the first list to an integer type.

So I thought I needed to step through each entry in listy. Does the problem stem from 'i' referencing the entry (ex: '341' and not index 0)? If so...how do you refer to the index? I thought that's what I was doing, but clearly not :(.

Any help would be much appreciated. I looked through some other questions posted to Stack with the same Type Error but I'm so new to this that they all just confused me further.

mcrocker
  • 1
  • 2
  • Not saying this is a clever approach ;-) but try `numlist = int(listy[int(i)])` as the i is a string and you need it as index number, thus add `int(i)`instead of just `i` inside ? Also numlist will always be replaced with next iteration ... – Dilettant Feb 19 '17 at 17:47
  • 3
    You should be using `list.append()` to add an element to the list. For adding all the element of one list to another, you may use `list.extend()` – Moinuddin Quadri Feb 19 '17 at 17:49
  • 1
    `numlist = list()` `listy = ['341', '22', '1803']` `for i in listy:` `numlist.append(int(i))` – Afaq Feb 19 '17 at 17:51
  • And yes, 'i' is referencing the entry (ex: '341' and not index 0). For accessing the index, you should be iterating using range as `for i in range(len(listy))` – Moinuddin Quadri Feb 19 '17 at 17:54
  • @Moinuddin Thank you for clarifying about the index, helps me understand the error! Also if I want to change each element to integer type is it most efficient to try to do that within the extend? Ex: numlist.extend(int(listy[i]) if that makes sense? Or better to write separate line of code to accomplish that? – mcrocker Feb 20 '17 at 18:03
  • @mcrocker take a look at: [Convert all strings in a list to int](http://stackoverflow.com/questions/7368789/convert-all-strings-in-a-list-to-int) – Moinuddin Quadri Feb 20 '17 at 18:06
  • Thank you for the links, I am learning about how to pose better questions and search for duplicates in stack overflow as a result! & Thanks for the suggested approaches :) – mcrocker Apr 08 '17 at 23:03

0 Answers0