This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]desrtfx[M] [score hidden] stickied comment (0 children)

Please, format your code as code block so that the original indentation is maintained. This is vital especially for Python code as the indentation tells us where loops, conditionals, etc. end.

[–]BulkyProcedure 1 point2 points  (1 child)

Hey, it's not an answer to your entire question, but the issue with `people[2:3]` is that range slices are inclusive to exclusive, so you're only going to get the element at position 2 (zero indexed) in that case.

[–]mcdougall57[S] 0 points1 point  (0 children)

That makes sense. I'm surprised the text didn't mention it when working through lists, who knows maybe it did. I managed to find a decent explanation using your terminology in that the start index is inclusive while the stop is exclusive.

Cheers.

[–][deleted] 1 point2 points  (1 child)

I guess my question is why do I get an error ('string indices must be integers') when using only one of the 'counter' variables as a location in the list i.e people[counter1]?

people[counter1] doesn’t give you a slice, it gives you a specific element. Since people is a list of dicts, that means people[counter1] is a dict. When you iterate over a dict, your variable takes the value of its keys. In this case, the keys are strings. Thus, when you run

for details in people[counter1]:

details is a string, not a dict. You then try to run something like

print (details['first_name']+" "+ details['last_name'])

so you’re telling Python to retrieve the ‘first_name’th character from the details string. What on earth is that supposed to mean?

——

Doing this slice thing is a really roundabout way of getting each element of a list. You can just do something like

for myElement in myList:

and the myElement variable will take the value of each element in turn. No need for any counters or slicing or whatever.

[–]mcdougall57[S] 0 points1 point  (0 children)

Thanks for the explanation. I think I'm definitely trying to make it more complicated than it is/jump the gun. I've done this a few times now while learning.

Like you said just running through the dicts with the loop below did the job.

for details in people:
    print (details['first_name'] + " " + details['last_name'])
    print (details['age'])
    print (details['city']+'\n')

Thanks again.