0

Backdrop

While fiddling with the map() function in my Python project, I tried to assign a variable, the python map object I intended to create once, and then reuse the same map object to use them as strings, lists or tuples, etc.

Brief reproduction of the problem:

def concat(n):
  return n + "abc"
def upp(Lst):
  for i in Lst:
    if i[0].isupper():
      return i
def low(Lst):
  for i in Lst:
    if i[0].islower():
      return i

#main
L = ["a","B","c"]
m = map(concat,L) #Creating a Python map object
print(f"Capitalised string: {upp(list(m))} lowercased string: {low(list(m))}") #Accessing the returned manipulated map object

Expected Output:

Capitalised string: Babc lowercased string: aabc

Problem:

Actual output:

Capitalised string: Babc lowercased string: None

#Manual Debugging:
u = upp(list(m))
l = low(list(m))
print(u,l)

Output:

["aabc","Babc","cabc"][]

So as you can see, the second time I try to retrieve the map object, it doesn't return anything in the list.

Final Question:

I want to know why is it so that the map object is not accessible even when it does exist.

Note:

  1. The following questions don't answer my question:

  2. Edits which improve the sample program which reproduces the problem will be welcomed.

  • 1
    `map` returns a generator, once a generator is fully consumed it will not yield anymore values when iterated. You need to re-create the generator to iterate over it again – Iain Shelvington Sep 17 '21 at 08:28
  • @IainShelvington I looked up the generator concept, but you see, I need to access the returned value multiple times, and possibly in different forms every time. So won't creating a `map` generator eveytime I need it add up to the code overhead? Is there a way we can evade re-creating it everytime? – Sapt-Programmer Sep 17 '21 at 09:01
  • 1
    You could just convert it to a list initially so you can re-use it: `m = list(map(concat,L))`. Then you don't need the calls to list in your string formatting – Iain Shelvington Sep 17 '21 at 09:02

0 Answers0