Home > OS >  Search from second to last item in array
Search from second to last item in array

Time:03-04

For a intro to python class i have an array of peoples home streets, this is what the array looks like.

[Clarkson Grove, Cheyyne Street, Quill Drive, Clarkson grove]

for this task i must take the first piece of data in the array, search through the rest of the array (I must start at record 2 and with the count = to 1) for the same street name, then add 1 to count if it is found.

When i try to run this code i get an error stating list object cannot be interpreted as integer, my records in the array obviously aren't integer they are strings.

This is what my code looks like

count=1
for i in range(adress[1:]):
    print(adress[i])
    count=count 1

CodePudding user response:

The range function accepts integers. But you are passing a list object.

There can be two solutions for that:

Soluton 1

Use len function

count=1
for i in range(len(adress[1:])):
    print(adress[1:][i])
    count=count 1

Solution 2

directly loop in array:

count=1
for each in adress[1:]:
    print(each)
    count=count 1

CodePudding user response:

You're seeing that exception because of this: range(adress[1:]). range expects an integer, but you provided a slice of the adress list. If you want to iterate from zero and forward, you're looking for range(len(adress[1:])). In the other hand, if you want to start from 1 and forward, you could use something like range(1, len(adress)) (starting from 1 and stoping where the list ends).

  • Related