Skip to content Skip to sidebar Skip to footer

Accessing The Value Of A Zip Object Using Its Index

I am trying to understand how to access a zip object and I'm trying to figure out how to access the value in the zipped object using the index by using the .index() just as we have

Solution 1:

It seems like you expect points to be a list, but zip objects are not lists.

If you want to convert it to a list, then do this:

points = list(zip(list1,list2))

Solution 2:

zip used to return a list in Python 2 but is now a generator in Python 3, so you would have to convert it to a list using the list constructor first before you can use the index method:

points = list(zip(list1,list2))

Solution 3:

As the others say: zip returns a zip object which is an iterator you can use to make other things like a list or a dictionary. Also, (a,b,c) returns a tuple whereas [a,b,c] returns a list.

>>> type((1,2,3))
<class'tuple'>
>>> type([1,2,3])
<class'list'>
>>> 

It may not matter to you unless you want to start modifying the contents of the "lists". You called them "lists" so I have made them lists below. In either case, once you zip them up and convert to a list (list(zip(list1,list2)), you get a list of tuples. In fact this makes your code a little easier because you can pass the tuple into your function:

deffind_neighbors(point):
i = point[0]
j = point[1]
print(f"List of neighbours of {point}: {[(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]}")
return [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]

list1 = [211,209,210,210,211]
list2 = [72,72,73,71,73]
pointsList = list(zip(list1,list2))

#These loops are just to show what is going on comment them out or delete themfor i in pointsList:
    print(i)
    print(f"The first element is {i[0]} and the second is {i[1]}")

#or let Python unpack the tuples - it depends what you wantfor i, j in pointsList:
    print(i,j)

for point in pointsList:
print(f"In the loop for find_neighbours of: {point}")
for testPoint in find_neighbors(point):
    print(f"Testing {testPoint}")
    if testPoint notin pointsList:
        print(f"Point {testPoint} is not there.")
        continueelif testPoint in pointsList:
        print(f"*******************Point {testPoint} is there.***************************")

Notice that I have added a point to your data that is a neighbour so that we can see the function find it. Have a think about the difference between lists and tuples before you commit too much work to one route or the other. My code is written in Python 3.7.

Finally, remember that you could use a dictionary pointDict = dict(zip(list1,list2)) which might be more use to you in your program especially if you need to look things up. It might be more pythonic.

Post a Comment for "Accessing The Value Of A Zip Object Using Its Index"