Home > Software design >  How to use "pop" method on zip() python
How to use "pop" method on zip() python

Time:09-05

I need to write a function that return the first tuple of a zip object, and than deletes this tuple. The object may contain several identical tuples, so using list comprehension is problematic - because I can't remove ANY tuple that is equivalent to the tuple I need to remove.

Thanks for your time reading and willing to help!

CodePudding user response:

Simple you just have to convert it to a list

languages = ['Java', 'Python', 'JavaScript']
versions = [14, 3, 6]

result = zip(languages, versions)
result_list = list(result)
print("old:", result_list)
result_list.pop()
print("new:", result_list)

Does this answer your question?

CodePudding user response:

taking the sample from ss3387, we can generate the list directly when using zip(). this list can be sliced, so that we don’t need any further step.

languages = ['Java', 'Python', 'JavaScript']
versions = [14, 3, 6]
result = list(zip(languages, versions))[1:]
print(result)

CodePudding user response:

Start with two lists (this code will support more than 2 lists) e.g.,

listA = ['colour', 'make', 'type']
listB = ['red', 'Ford', 'saloon']

Now write a function that calls zip to acquire a tuple representing the first elements from each of the lists (of course using zip for this is unnecessary but for some reason known only to OP is a requirement)

def get_tuple_and_remove(*args):
    t = next(zip(*args))
    for arg in args:
        arg.pop(0)
    return t

Now...

print(get_tuple_and_remove(listA, listB))

print(listA)
print(listB)

Output:

('colour', 'red')
['make', 'type']
['Ford', 'saloon']

The same functionality could be achieved without zip like this:

def get_tuple_and_remove(*args):
    return tuple(a.pop(0) for a in args)
  • Related