Jump to content

Problem with understanding Python code: index, colon, curly brackets and scope of loop


zak100

Recommended Posts

Hi,

I have written the following Python program:

1.a= ["a", "f", "bar", "b","a", "aaaaa"]

2.ind = {a[i]:i for i in range(len(a))}

3.print(ind)

4.print("ind['a']= {0}".format(ind['a']))

5.print("a[5]= {0}, a[4]= {1}, a[3]= {2}, a[2] = {3}, a[1] = {4}, a[0]= {5}".format(a[5],a[4], a[3], a[2], a[1], a[0]))

output is:

Quote

 

{'a': 4, 'f': 1, 'bar': 2, 'b': 3, 'aaaaa': 5}

ind['a']= 4

a[5]= aaaaa, a[4]= a, a[3]= b, a[2] = bar, a[1] = f, a[0]= a

 

 

 

Line #1 , I can understand, we are creating an array of 6 elements, starting index is 0 and end index is 5. I can’t understand following things in line#2:

a) what is the purpose of ‘ind’ variabel?

b) What is the purpose of curly bracket in line#2

c)What is the purpose of colon in line#2

d) Which statements are under the impact of ‘for’ loop and how will we know that the scope of ‘for’ loop has ended?

e) There are two enteries for ‘a’ in the array, why I am getting the index for “ind[‘a’] as 4.

 

Somebody please guide me

 

Zulfi.

Link to comment
Share on other sites

a) The variable is a map (in Python language: a dictionary or dict). Maps are pairs of unique keys and possibly non-unique values. Typical cases are lists of usernames (as keys) and the users' passwords (as values for the keys). In your case it is a map of string keys that each have an integer value.

b) The curly brackets are a way to define dicts in Python. You should be able to literally type in a dict like "{'a':0, 'b':1, 'c':2}". Here, the case is just a bit more complicated because the term is { <elements are generated by a for-loop> }.

c) The colon separates key and value in a dict, as in my example from case b). The loop generates key:value pairs a:i for all i in range.

d) The statements are the a:i. The loop runs from 0 to len(a)-1. In this case from 0 to 5.

e) As mentioned before, keys in a map are unique. So there can only be at most one value for the key 'a'. The usual behavior for maps and dicts is that setting d[key] = value will either create a key with the given value in d. Or, if the key already exists, it will keep the key and set the value to the new one given. In that context, it is at least the behavior I would expect from the loop: At i=0, it sets ind['a']=0. And then at i=4 it overrides the existing value with ind['a'] = 4.

Link to comment
Share on other sites

  • 3 months later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.