Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List Iteration in Python

So i get this error:

TypeError: list indices must be integers, not str

pointing to this line of code:

if snarePattern[i] == '*':

whenever I use what I thought was simple Python

snarePattern = ['-', '*', '-', '*']
for i in snarePattern:
    if snarePattern[i] == '*':
        ...

Is this not allowed? What don't I know?

And also, If anyone knows where I'm going with this code, can you think of an easier way to create and parse simple patterns like this??? I'm new to Python.

Thanks guys

like image 229
DanMoore Avatar asked Nov 20 '25 17:11

DanMoore


1 Answers

for i in snarePattern: goes through each item not each index:

>>> snarePattern = ['-', '*', '-', '*']
>>> for c in snarePattern:
        print c


-
*
-
*

You can change it to

for i in range(len(snarePattern)):

if you really need it, but it looks like you don't, just check if c == '*' for example.

A better way to go through indices is

for i, c in enumerate(snarePattern):  # i is each index, c is each character
like image 164
jamylak Avatar answered Nov 23 '25 05:11

jamylak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!