-2

I see that zip(<>) in python does not take duplicates. Is there a way to make it consider duplicates? The following are my two lists:

[933, 933, 933, 933, 933, 1129, 1129, 1129, 1129]
[4139, 6597069777240, 10995116284808, 32985348833579, 32985348838375, 1242, 2199023262543, 6597069771886, 6597069776731]

When I am trying to loop the lists simultaneously using zip(), only(933, 4139) and (1129, 1242) are being considered. Is there a way(using zip) to avoid this and make it consider all the values in the lists.

Thanks in advance

  • List item
sindhuja
  • 167
  • 1
  • 12
  • 6
    .. could you give a [mcve] of your problem? zip can handle dups, so it's more likely the problem is elsewhere. – DSM Aug 16 '18 at 19:46

1 Answers1

5

Perhaps you're not using it correctly, because zip() does not remove duplicates - see:

a = [933, 933, 933, 933, 933, 1129, 1129, 1129, 1129]
b = [4139, 6597069777240, 10995116284808, 32985348833579, 32985348838375, 1242, 2199023262543, 6597069771886, 6597069776731]

for x, y in zip(a, b):
    print((x, y))

Will print:

(933, 4139)
(933, 6597069777240)
(933, 10995116284808)
(933, 32985348833579)
(933, 32985348838375)
(1129, 1242)
(1129, 2199023262543)
(1129, 6597069771886)
(1129, 6597069776731)
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • okay! I am new to python lists and this is how I am using zip():for src, tgt in zip(a, b): if src not in adj_list: adj_list[src] = tgt where adj_list is an empty dictionary and this is what I get: {933: 4139, 1129: 1242} so i thought zip() does not consider duplicates. My bad! So why is zip behaving weird when we loop through it? Or I am going wrong some where? – sindhuja Aug 16 '18 at 20:06
  • The `not in` part is filtering out duplicates, you can only add a key _once_ to a dictionary, after the first one the `if`condition will prevent adding it again. This has nothing to do with `zip()`, better familiarise yourself with the way dictionaries work. – Óscar López Aug 16 '18 at 20:14
  • Just to be clear: even if you remove the `if`it won't work, what would happen is that the key gets its value overwritten every time you add it again. Bottom line: a dictionary cannot have duplicate keys! think about what you _really_ need - maybe a dictionary but with a _list_ of elements as values for each key? or no dictionary at all, just a list of tuples as the ones in my answer? – Óscar López Aug 16 '18 at 20:29
  • Okay, I see what you are saying, I ll edit the question.. Thanks! – sindhuja Aug 16 '18 at 21:04
  • There is no need to edit this question, it has been asked before. Take a look at this [post](https://stackoverflow.com/q/5378231/201359). – Óscar López Aug 16 '18 at 21:09