why does map work like izip_longest with fill=none?

  • Last Update :
  • Techknowledgy :

To get the result you want I would suggest using itertools.izip_longest with a sentinel value(object()) rather than default None, None will break things if the iterables itself contain None:

from itertools
import izip_longest

def solve(seq):
   sentinel = object()
return [tuple(x
      for x in item
      if x is not sentinel) for item in
   izip_longest( * seq, fillvalue = sentinel)
]

print solve([
   [1, 2, 3, 4],
   [5, 6]
])
#[(1, 5), (2, 6), (3, ), (4, )]

Given that the first list is always longer and that there are only two lists, you would do something like this:

x = [1, 2, 3, 4, 5]
y = ['a', 'b']
zip(x, y) + [(i, ) for i in x[len(y): ]]
   [(1, 'a'), (2, 'b'), (3, ), (4, ), (5, )]

Suggestion : 2

Make an iterator that returns object over and over again. Runs indefinitely unless the times argument is specified. Used as argument to map() for invariant parameters to the called function. Also used with zip() to create an invariant part of a tuple record.,Make an iterator that returns evenly spaced values starting with number start. Often used as an argument to map() to generate consecutive data points. Also, used with zip() to add sequence numbers. Roughly equivalent to:,Make an iterator that returns accumulated sums, or accumulated results of other binary functions (specified via the optional func argument).,Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely. Roughly equivalent to:

def accumulate(iterable, func = operator.add, *, initial = None):
   'Return running totals'
# accumulate([1, 2, 3, 4, 5]) -- > 1 3 6 10 15
# accumulate([1, 2, 3, 4, 5], initial = 100) -- > 100 101 103 106 110 115
# accumulate([1, 2, 3, 4, 5], operator.mul) -- > 1 2 6 24 120
it = iter(iterable)
total = initial
if initial is None:
   try:
   total = next(it)
except StopIteration:
   return
yield total
for element in it:
   total = func(total, element)
yield total
>>> data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8] >>>
   list(accumulate(data, operator.mul)) # running product[3, 12, 72, 144, 144, 1296, 0, 0, 0, 0] >>>
   list(accumulate(data, max)) # running maximum[3, 4, 6, 6, 6, 9, 9, 9, 9, 9]

# Amortize a 5 % loan of 1000 with 4 annual payments of 90 >>>
   cashflows = [1000, -90, -90, -90, -90] >>>
   list(accumulate(cashflows, lambda bal, pmt: bal * 1.05 + pmt))[1000, 960.0, 918.0, 873.9000000000001, 827.5950000000001]

# Chaotic recurrence relation https: //en.wikipedia.org/wiki/Logistic_map
   >>>
   logistic_map = lambda x, _: r * x * (1 - x) >>>
   r = 3.8 >>>
   x0 = 0.4 >>>
   inputs = repeat(x0, 36) # only the initial value is used >>>
   [format(x, '.2f') for x in accumulate(inputs, logistic_map)]
   ['0.40', '0.91', '0.30', '0.81', '0.60', '0.92', '0.29', '0.79', '0.63',
      '0.88', '0.39', '0.90', '0.33', '0.84', '0.52', '0.95', '0.18', '0.57',
      '0.93', '0.25', '0.71', '0.79', '0.63', '0.88', '0.39', '0.91', '0.32',
      '0.83', '0.54', '0.95', '0.20', '0.60', '0.91', '0.30', '0.80', '0.60'
   ]
def chain( * iterables):
   # chain('ABC', 'DEF') -- > A B C D E F
for it in iterables:
   for element in it:
   yield element
def from_iterable(iterables):
   # chain.from_iterable(['ABC', 'DEF']) -- > A B C D E F
for it in iterables:
   for element in it:
   yield element
def combinations(iterable, r):
   # combinations('ABCD', 2) -- > AB AC AD BC BD CD
# combinations(range(4), 3) -- > 012 013 023 123
pool = tuple(iterable)
n = len(pool)
if r > n:
   return
indices = list(range(r))
yield tuple(pool[i]
   for i in indices)
while True:
   for i in reversed(range(r)):
   if indices[i] != i + n - r:
   break
else:
   return
indices[i] += 1
for j in range(i + 1, r):
   indices[j] = indices[j - 1] + 1
yield tuple(pool[i]
   for i in indices)
def combinations(iterable, r):
   pool = tuple(iterable)
n = len(pool)
for indices in permutations(range(n), r):
   if sorted(indices) == list(indices):
   yield tuple(pool[i]
      for i in indices)

Suggestion : 3

Last Updated : 27 Feb, 2020

Syntax:

zip_longest(iterable1, iterable2, fillval)

Output:

The combined values of iterables is:
   ('G', 'e')('e', 'k')('s', 'f')('o', 'r')('G', 'e')('e', 'k')('s', '_')

Suggestion : 4

If one of the iterables is potentially infinite, then the izip_longest() function should be wrapped with something that limits the number of calls (for example islice() or takewhile()). If not specified, fillvalue defaults to None.,Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence. Equivalent to:,Make an iterator that filters elements from data returning only those that have a corresponding element in selectors that evaluates to True. Stops when either the data or selectors iterables has been exhausted. Equivalent to:,Make an iterator that computes the function using arguments from each of the iterables. If function is set to None, then imap() returns the arguments as a tuple. Like map() but stops when the shortest iterable is exhausted instead of filling in None for shorter iterables. The reason for the difference is that infinite iterator arguments are typically an error for map() (because the output is fully evaluated) but represent a common and useful way of supplying arguments to imap(). Equivalent to:

def chain( * iterables):
   # chain('ABC', 'DEF') -- > A B C D E F
for it in iterables:
   for element in it:
   yield element
@classmethod
def from_iterable(iterables):
   # chain.from_iterable(['ABC', 'DEF']) -- > A B C D E F
for it in iterables:
   for element in it:
   yield element
def combinations(iterable, r):
   # combinations('ABCD', 2) -- > AB AC AD BC BD CD
# combinations(range(4), 3) -- > 012 013 023 123
pool = tuple(iterable)
n = len(pool)
if r > n:
   return
indices = range(r)
yield tuple(pool[i]
   for i in indices)
while True:
   for i in reversed(range(r)):
   if indices[i] != i + n - r:
   break
else:
   return
indices[i] += 1
for j in range(i + 1, r):
   indices[j] = indices[j - 1] + 1
yield tuple(pool[i]
   for i in indices)
def combinations(iterable, r):
   pool = tuple(iterable)
n = len(pool)
for indices in permutations(range(n), r):
   if sorted(indices) == list(indices):
   yield tuple(pool[i]
      for i in indices)
def combinations_with_replacement(iterable, r):
   # combinations_with_replacement('ABC', 2) -- > AA AB AC BB BC CC
pool = tuple(iterable)
n = len(pool)
if not n and r:
   return
indices = [0] * r
yield tuple(pool[i]
   for i in indices)
while True:
   for i in reversed(range(r)):
   if indices[i] != n - 1:
   break
else:
   return
indices[i: ] = [indices[i] + 1] * (r - i)
yield tuple(pool[i]
   for i in indices)
def combinations_with_replacement(iterable, r):
   pool = tuple(iterable)
n = len(pool)
for indices in product(range(n), repeat = r):
   if sorted(indices) == list(indices):
   yield tuple(pool[i]
      for i in indices)

Suggestion : 5

Moreover, when passing more than one iterable as argument in Python 2, map pads the shorter iterables with None (similar to itertools.izip_longest). In Python 3, iteration stops after the shortest iterable.,In Python 2, you can pass None to serve as an identity function. This no longer works in Python 3.,map() is a builtin that is useful for applying a function to elements of an iterable. In Python 2, map returns a list. In Python 3, map returns a map object, which is a generator.,Note: instead of map consider using list comprehensions, which are Python 2/3 compatible. Replacing map(str, [1, 2, 3, 4, 5]):

map() is a builtin that is useful for applying a function to elements of an iterable. In Python 2, map returns a list. In Python 3, map returns a map object, which is a generator.

# Python 2.X
>>> map(str, [1, 2, 3, 4, 5])
['1', '2', '3', '4', '5']
>>> type(_)
>>> <class 'list'>

   # Python 3.X
   >>> map(str, [1, 2, 3, 4, 5])
   <map object at 0x*>
      >>> type(_)
      <class 'map'>

         # We need to apply map again because we "consumed" the previous map....
         >>> map(str, [1, 2, 3, 4, 5])
         >>> list(_)
         ['1', '2', '3', '4', '5']
2._
>>> map(None, [0, 1, 2, 3, 0, 4])[0, 1, 2, 3, 0, 4]
3._
>>> list(map(None, [0, 1, 2, 3, 0, 5]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
      TypeError: 'NoneType' object is not callable
5._
>>> list(map(lambda x, y, z: (x, y, z), [1, 2, 3], [1, 2], [1, 2, 3, 4, 5]))[(1, 1, 1), (2, 2, 2)]

# to obtain the same padding as in Python 2 use zip_longest from itertools
   >>>
   import itertools >>>
   list(itertools.zip_longest([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]))[(1, 1, 1), (2, 2, 2), (3, None, 3), (None, None, 4), (None, None, 5)]

Note: instead of map consider using list comprehensions, which are Python 2/3 compatible. Replacing map(str, [1, 2, 3, 4, 5]):

>>> [str(i) for i in [1, 2, 3, 4, 5]]
['1', '2', '3', '4', '5']
>>> map(None, [0, 1, 2, 3, 0, 4])[0, 1, 2, 3, 0, 4]
>>> list(map(None, [0, 1, 2, 3, 0, 5]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
      TypeError: 'NoneType' object is not callable
>>> map(None, [1, 2, 3], [1, 2], [1, 2, 3, 4, 5])[(1, 1, 1), (2, 2, 2), (3, None, 3), (None, None, 4), (None, None, 5)]
>>> list(map(lambda x, y, z: (x, y, z), [1, 2, 3], [1, 2], [1, 2, 3, 4, 5]))[(1, 1, 1), (2, 2, 2)]

# to obtain the same padding as in Python 2 use zip_longest from itertools
   >>>
   import itertools >>>
   list(itertools.zip_longest([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]))[(1, 1, 1), (2, 2, 2), (3, None, 3), (None, None, 4), (None, None, 5)]

Suggestion : 6

Last modified: Jul 16, 2022, by MDN contributors

const wrongMap = new Map()
wrongMap['bla'] = 'blaa'
wrongMap['bla2'] = 'blaaa2'

console.log(wrongMap) // Map { bla: 'blaa', bla2: 'blaaa2' }
wrongMap.has('bla') // false
wrongMap.delete('bla') // false
console.log(wrongMap) // Map { bla: 'blaa', bla2: 'blaaa2' }
const contacts = new Map()
contacts.set('Jessie', {
   phone: "213-555-1234",
   address: "123 N 1st Ave"
})
contacts.has('Jessie') // true
contacts.get('Hilary') // undefined
contacts.set('Hilary', {
   phone: "617-555-4321",
   address: "321 S 2nd St"
})
contacts.get('Jessie') // {phone: "213-555-1234", address: "123 N 1st Ave"}
contacts.delete('Raymond') // false
contacts.delete('Jessie') // true
console.log(contacts.size) // 1
const myMap = new Map()

const keyString = 'a string'
const keyObj = {}
const keyFunc = function() {}

// setting the values
myMap.set(keyString, "value associated with 'a string'")
myMap.set(keyObj, 'value associated with keyObj')
myMap.set(keyFunc, 'value associated with keyFunc')

myMap.size // 3

// getting the values
myMap.get(keyString) // "value associated with 'a string'"
myMap.get(keyObj) // "value associated with keyObj"
myMap.get(keyFunc) // "value associated with keyFunc"

myMap.get('a string') // "value associated with 'a string'"
// because keyString === 'a string'
myMap.get({}) // undefined, because keyObj !== {}
myMap.get(function() {}) // undefined, because keyFunc !== function () {}
const myMap = new Map()
myMap.set(NaN, 'not a number')

myMap.get(NaN)
// "not a number"

const otherNaN = Number('foo')
myMap.get(otherNaN)
// "not a number"
const myMap = new Map()
myMap.set(0, 'zero')
myMap.set(1, 'one')

for (const [key, value] of myMap) {
   console.log(key + ' = ' + value)
}
// 0 = zero
// 1 = one

for (const key of myMap.keys()) {
   console.log(key)
}
// 0
// 1

for (const value of myMap.values()) {
   console.log(value)
}
// zero
// one

for (const [key, value] of myMap.entries()) {
   console.log(key + ' = ' + value)
}
// 0 = zero
// 1 = one