Why zip() function create key and values inside tuple when combine with two list

When we combine list using zip() function it create key and value inside tuple. Why is that. and why it is needed?

num = [1, 2, 3]
a = ['A', 'B', 'A']
new_list = zip(num, a)
print(list(new_list))
#result: [(1,'A'), (2,'B'), (3, 'A')]

The zip function always return the values as tuples- zip function. It’s just the simplest sequence type to use.

1 Like

And it is immutable. The corresponding values are fixed.

1 Like

Thanks. One more thing I would like to ask
In this case, we used

num = [1, 2, 3]
a = ['A', 'B', 'A']
new_list = zip(num, a)
print(list(new_list))
print(list(new_list))

We used list(new_list) to convert it into list datatype. right?
For Dictionary, when we combine two lists. Suppose
num = [1, 2, 3]
a = ['A', 'B', 'A']
to form a Dictionary
After using zip()
new_list = zip(num, a)
We use List Comprehension
new_dictionary = {key:value for key, value in new_list}
print(new_dictionary)
And not
print(dict(new_list)
Why can’t we use print(dict(new_list) to create dictionary as we used print(list(new_list)) to create list

but why immutable datatype is needed when two lists are combined. What is logic behind it
also help with the about query

I’d avoid naming your intermediate step new_list as it might to be a touch confusing.

I’m not 100% sure what your query is but you can use dict(zip(data1, data2)) assuming your values in data1 are hashable because it can accept an iterable of key:value pairs- Built-in Types — Python 3.9.1 documentation. Why not try it on your example?

So they cannot lose their association with one another. Corresponding values from all the lists are bound to the same tuple, in the order of the lists when they are zipped. This is important since it is predictable.

1 Like

No, lists can contain mutable data types but even if it didn’t then the list itself is a mutable data structure and therefore not hashable. You could use a tuple as a dictionary key, but only when the tuple doesn’t contain unhashable data types, (1, 2) for example is a valid key (two ints), (1, [2]) would not be (one int, one list).

2 Likes

Thanks it cleard my doubt.
Yes a list can also have list within list. Forgot about that