Repository: sympy/sympy

Issue:
Replace map() with a list compression in most cases
```
If you've been programming in Python for long enough, you know about the magic of list comprehensions.  They can 
make what would otherwise be a short for loop or a map() into a very simple, easy to understand, one line 
expression.  

Before they were introduced, the best way to do this sort of thing was with the use of map(), and probably a lambda 
function.  But anything that uses lambda is very difficult to read, and map() even without lambda is harder to read 
than a list compression in almost all cases.  

So I think we should replace most instances of map in the code with a list comprehension.  The exception might be 
the use of f, g, h = map(Function, 'fgh') in the docstrings.  map(lambda… is the worst in my opinion, and git gr 
'map(lambda' reveals around 25 of these.  

Of course, performance is also an issue.  While we should test the performance of each instance that we actually 
change, here are some simple benchmarks:

###
First, cache the function and the list.
###
In [1]: def f(x):
   ...:     return x**2
   ...: 

In [2]: a = range(100)

In [4]: %timeit map(f, a)
10000 loops, best of 3: 128 us per loop

In [5]: %timeit [f(x) for x in a]
10000 loops, best of 3: 162 us per loop

###
So map is slightly faster in this case.  
But what if we don't cache the function or the list, but use lambda instead?
###

In [8]: %timeit map(lambda x: x**2, range(100))
10000 loops, best of 3: 145 us per loop

In [9]: %timeit [x**2 for x in range(100)]
10000 loops, best of 3: 64.4 us per loop

###
The use of lambda actually makes map 2x slower than a list comprehension.
It becomes even clearer if we cache only the list.
###

In [10]: %timeit [x**2 for x in a]
10000 loops, best of 3: 58.9 us per loop

In [11]: %timeit map(lambda x: x**2, a)
10000 loops, best of 3: 158 us per loop

In [12]: %timeit map(lambda x: f(x), a)
10000 loops, best of 3: 246 us per loop

###
Which is 3x faster for list comprehensions, or 6x if lambda is used
unnecessarily, which it actually doesn't seem to be anywhere in sympy.  

lambda is usually used to call a multi-argument function with map()
###
In [13]: def g(x, y):
   ....:     return x**2*y
   ....: 


In [14]: %timeit map(lambda x: g(x, 10), a)
1000 loops, best of 3: 313 us per loop

In [15]: %timeit [g(x, 10) for x in a]
10000 loops, best of 3: 212 us per loop

###
One last example I ran (x is a Symbol):
###

In [6]: %timeit [x**i for i in range(100)]
1000 loops, best of 3: 2.78 ms per loop

In [7]: %timeit map(lambda i: x**i, range(100))
1000 loops, best of 3: 2.81 ms per loop

I've already done this for ode.py in my WIP ode-coverage branch.
```
Original issue for #4940: http://code.google.com/p/sympy/issues/detail?id=1841
Original author: https://code.google.com/u/asmeurer@gmail.com/
Original owner: https://code.google.com/u/asmeurer@gmail.com/


Discussion:
toolforger: Looks good to me. However, I'm not familiar enough with list comprehensions to be 100% sure that lambda expression and list comprehension are always equivalent, so somebody else will have to verify that.

I have made a few proposals for further improvement, but there's always the case of "do not fix more than one thing at a time in a PR, so it remains reviewable"; so maybe it's better to postpone these to a subsequent PR.
jcrist: Looks good, besides my one last comment. Please fix, and squash your commits into one. Will merge after that.

Patch:
diff --git a/sympy/combinatorics/partitions.py b/sympy/combinatorics/partitions.py
index 5e7147b80e..a98decdda7 100644
--- a/sympy/combinatorics/partitions.py
+++ b/sympy/combinatorics/partitions.py
@@ -58,7 +58,7 @@ def __new__(cls, *partition):
         if has_dups(partition):
             raise ValueError("Partition contained duplicated elements.")
 
-        obj = FiniteSet.__new__(cls, *list(map(lambda x: FiniteSet(*x), args)))
+        obj = FiniteSet.__new__(cls, *[FiniteSet(*x) for x in args])
         obj.members = tuple(partition)
         obj.size = len(partition)
         return obj
diff --git a/sympy/core/function.py b/sympy/core/function.py
index 56bb4a4959..aa23188d22 100644
--- a/sympy/core/function.py
+++ b/sympy/core/function.py
@@ -1299,7 +1299,7 @@ def _eval_subs(self, old, new):
                 if match:
                     variables = self_vars_front + self_vars
                     return Derivative(new, *variables)
-        return Derivative(*map(lambda x: x._subs(old, new), self.args))
+        return Derivative(*(x._subs(old, new) for x in self.args))
 
     def _eval_lseries(self, x, logx):
         dx = self.args[1:]
diff --git a/sympy/functions/elementary/complexes.py b/sympy/functions/elementary/complexes.py
index 1a5987b2a2..3b89505812 100644
--- a/sympy/functions/elementary/complexes.py
+++ b/sympy/functions/elementary/complexes.py
@@ -82,8 +82,7 @@ def eval(cls, arg):
                         included.append(term)
 
             if len(args) != len(included):
-                a, b, c = map(lambda xs: Add(*xs),
-                    [included, reverted, excluded])
+                a, b, c = (Add(*xs) for xs in [included, reverted, excluded])
 
                 return cls(a) - im(b) + c
 
@@ -178,8 +177,7 @@ def eval(cls, arg):
                         included.append(term)
 
             if len(args) != len(included):
-                a, b, c = map(lambda xs: Add(*xs),
-                    [included, reverted, excluded])
+                a, b, c = (Add(*xs) for xs in [included, reverted, excluded])
 
                 return cls(a) + re(b) + c
 
diff --git a/sympy/galgebra/ga.py b/sympy/galgebra/ga.py
index f597f5a173..ec7733748d 100644
--- a/sympy/galgebra/ga.py
+++ b/sympy/galgebra/ga.py
@@ -285,14 +285,14 @@ def make_vector(self, base):  # make a vector (grade 1)
                 if self.fct:
                     base_lst = str_combinations(base, MV.coords, rank=1, mode='__')
                     fct_lst = fct_sym_array(base_lst, MV.coords)
-                    self.obj = reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[1]))))
+                    self.obj = reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[1])))
                 else:
                     if MV.coords is not None:
                         base_lst = str_combinations(base, MV.coords, rank=1, mode='__')
                     else:
                         base_lst = str_combinations(base, MV.subscripts, rank=1, mode='__')
                     fct_lst = fct_sym_array(base_lst, None)
-                    self.obj = reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[1]))))
+                    self.obj = reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[1])))
             else:
                 result = S.Zero
                 for (coef, base) in zip(base, MV.blades[1]):
@@ -316,14 +316,14 @@ def make_grade(self, base):  # if base is 'A,n' then make a grade n multivector
                 if self.fct:
                     base_lst = str_combinations(base, MV.coords, rank=n, mode='__')
                     fct_lst = fct_sym_array(base_lst, MV.coords)
-                    self.obj = reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[n]))))
+                    self.obj = reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[n])))
                 else:
                     if MV.coords is not None:
                         base_lst = str_combinations(base, MV.coords, rank=n, mode='__')
                     else:
                         base_lst = str_combinations(base, MV.subscripts, rank=n, mode='__')
                     fct_lst = fct_sym_array(base_lst, None)
-                    self.obj = reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[n]))))
+                    self.obj = reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[n])))
             else:
                 raise TypeError('Cannot make_grade for base = %s' % base)
             self.igrade = n
@@ -335,14 +335,14 @@ def make_grade2(self, base):  # grade 2 multivector
                 if self.fct:
                     base_lst = str_combinations(base, MV.coords, rank=2, mode='__')
                     fct_lst = fct_sym_array(base_lst, MV.coords)
-                    self.obj = reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[2]))))
+                    self.obj = reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[2])))
                 else:
                     if MV.coords is not None:
                         base_lst = str_combinations(base, MV.coords, rank=2, mode='__')
                     else:
                         base_lst = str_combinations(base, MV.subscripts, rank=2, mode='__')
                     fct_lst = fct_sym_array(base_lst, None)
-                    self.obj = reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[2]))))
+                    self.obj = reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[2])))
             else:
                 raise TypeError('!!!!Cannot make_grade2 for base = ' + str(base) + '!!!!\n')
             self.igrade = 2
@@ -354,14 +354,14 @@ def make_pseudo(self, base):  # multivector of grade MV.dim
                 if self.fct:
                     base_lst = str_combinations(base, MV.coords, rank=MV.dim, mode='__')
                     fct_lst = fct_sym_array(base_lst, MV.coords)
-                    self.obj = reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[MV.dim]))))
+                    self.obj = reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[MV.dim])))
                 else:
                     if MV.coords is not None:
                         base_lst = str_combinations(base, MV.coords, rank=MV.dim, mode='__')
                     else:
                         base_lst = str_combinations(base, MV.subscripts, rank=MV.dim, mode='__')
                     fct_lst = fct_sym_array(base_lst, None)
-                    self.obj = reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[MV.dim]))))
+                    self.obj = reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[MV.dim])))
             else:
                 raise TypeError('!!!!Cannot make_pseudo for base = ' + str(base) + '!!!!\n')
             self.igrade = MV.dim
@@ -378,14 +378,14 @@ def make_spinor(self, base):  # multivector with all even grades
                     if self.fct:
                         base_lst = str_combinations(base, MV.coords, rank=rank, mode='__')
                         fct_lst = fct_sym_array(base_lst, MV.coords)
-                        self.obj += reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[rank]))))
+                        self.obj += reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[rank])))
                     else:
                         if MV.coords is not None:
                             base_lst = str_combinations(base, MV.coords, rank=rank, mode='__')
                         else:
                             base_lst = str_combinations(base, MV.subscripts, rank=rank, mode='__')
                         fct_lst = fct_sym_array(base_lst, None)
-                        self.obj += reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[rank]))))
+                        self.obj += reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[rank])))
             else:
                 raise TypeError('Cannot make_mv for base = %s' % base)
             self.igrade = -1
@@ -402,14 +402,14 @@ def make_mv(self, base):
                     if self.fct:
                         base_lst = str_combinations(base, MV.coords, rank=rank, mode='__')
                         fct_lst = fct_sym_array(base_lst, MV.coords)
-                        self.obj += reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[rank]))))
+                        self.obj += reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[rank])))
                     else:
                         if MV.coords is not None:
                             base_lst = str_combinations(base, MV.coords, rank=rank, mode='__')
                         else:
                             base_lst = str_combinations(base, MV.subscripts, rank=rank, mode='__')
                         fct_lst = fct_sym_array(base_lst, None)
-                        self.obj += reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[rank]))))
+                        self.obj += reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[rank])))
             else:
                 raise TypeError('!!!!Cannot make_mv for base = ' + str(base) + '!!!!\n')
             self.igrade = -1
diff --git a/sympy/galgebra/stringarrays.py b/sympy/galgebra/stringarrays.py
index 34ebca2984..2e97cfcde5 100644
--- a/sympy/galgebra/stringarrays.py
+++ b/sympy/galgebra/stringarrays.py
@@ -103,6 +103,7 @@ def str_combinations(base, lst, rank=1, mode='_'):
     forming the 'indexes' by concatenating combinations of elements from
     'lst' taken 'rank' at a time.
     """
-    str_lst = list(map(lambda x: base + mode + x, map(lambda x: reduce(operator.add, x),
-                        combinations(map(lambda x: str(x), lst), rank))))
+    a1 = combinations([str(x) for x in lst], rank)
+    a2 = [reduce(operator.add, x) for x in a1]
+    str_lst = [base + mode + x for x in a2]
     return str_lst
diff --git a/sympy/matrices/dense.py b/sympy/matrices/dense.py
index 7289638224..2555ea86a1 100644
--- a/sympy/matrices/dense.py
+++ b/sympy/matrices/dense.py
@@ -804,8 +804,7 @@ def col_op(self, j, f):
         col
         row_op
         """
-        self._mat[j::self.cols] = list(map(lambda t: f(*t),
-            list(zip(self._mat[j::self.cols], list(range(self.rows))))))
+        self._mat[j::self.cols] = [f(*t) for t in list(zip(self._mat[j::self.cols], list(range(self.rows))))]
 
     def row_swap(self, i, j):
         """Swap the two given rows of the matrix in-place.
diff --git a/sympy/matrices/matrices.py b/sympy/matrices/matrices.py
index 864b2ab17e..927ea291cd 100644
--- a/sympy/matrices/matrices.py
+++ b/sympy/matrices/matrices.py
@@ -562,7 +562,7 @@ def __add__(self, other):
             blst = B.tolist()
             ret = [S.Zero]*A.rows
             for i in range(A.shape[0]):
-                ret[i] = list(map(lambda j, k: j + k, alst[i], blst[i]))
+                ret[i] = [j + k for j, k in zip(alst[i], blst[i])]
             rv = classof(A, B)._new(ret)
             if 0 in A.shape:
                 rv = rv.reshape(*A.shape)
diff --git a/sympy/physics/quantum/operatorset.py b/sympy/physics/quantum/operatorset.py
index 0faa70b95c..26e2f5c687 100644
--- a/sympy/physics/quantum/operatorset.py
+++ b/sympy/physics/quantum/operatorset.py
@@ -262,7 +262,7 @@ def _get_ops(state_inst, op_classes, **options):
         ret = state_inst._state_to_operators(op_classes, **options)
     except NotImplementedError:
         if isinstance(op_classes, (set, tuple, frozenset)):
-            ret = tuple(map(lambda x: _make_default(x), op_classes))
+            ret = tuple(_make_default(x) for x in op_classes)
         else:
             ret = _make_default(op_classes)
 
diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py
index d3ee4523d3..c619b1d4c8 100644
--- a/sympy/printing/latex.py
+++ b/sympy/printing/latex.py
@@ -87,10 +87,10 @@
     'scr': lambda s: r'\mathscr{'+s+r'}',
     'frak': lambda s: r'\mathfrak{'+s+r'}',
     # Brackets
-    'norm': lambda s: r'\left\|{'+s+r'}\right\|',
+    'norm': lambda s: r'\left\lVert{'+s+r'}\right\rVert',
     'avg': lambda s: r'\left\langle{'+s+r'}\right\rangle',
     'abs': lambda s: r'\left|{'+s+r'}\right|',
-    'mag': lambda s: r'\left|{'+s+r'}\right|',
+    'mag': lambda s: r'\left\lvert{'+s+r'}\right\rvert',
 }
 
 greek_letters_set = frozenset(greeks)
@@ -1449,7 +1449,7 @@ def _print_KroneckerDelta(self, expr, exp=None):
 
     def _print_LeviCivita(self, expr, exp=None):
         indices = map(self._print, expr.args)
-        if all(map(lambda x: x.is_Atom, expr.args)):
+        if all(x.is_Atom for x in expr.args):
             tex = r'\varepsilon_{%s}' % " ".join(indices)
         else:
             tex = r'\varepsilon_{%s}' % ", ".join(indices)
diff --git a/sympy/printing/octave.py b/sympy/printing/octave.py
index 2b25c57492..b7b28f561d 100644
--- a/sympy/printing/octave.py
+++ b/sympy/printing/octave.py
@@ -149,8 +149,8 @@ def _print_Mul(self, expr):
 
         a = a or [S.One]
 
-        a_str = list(map(lambda x: self.parenthesize(x, prec), a))
-        b_str = list(map(lambda x: self.parenthesize(x, prec), b))
+        a_str = [self.parenthesize(x, prec) for x in a]
+        b_str = [self.parenthesize(x, prec) for x in b]
 
         # from here it differs from str.py to deal with "*" and ".*"
         def multjoin(a, a_str):
diff --git a/sympy/printing/str.py b/sympy/printing/str.py
index 63012e2940..29b4ce5979 100644
--- a/sympy/printing/str.py
+++ b/sympy/printing/str.py
@@ -280,8 +280,8 @@ def _print_Mul(self, expr):
 
         a = a or [S.One]
 
-        a_str = list(map(lambda x: self.parenthesize(x, prec), a))
-        b_str = list(map(lambda x: self.parenthesize(x, prec), b))
+        a_str = [self.parenthesize(x, prec) for x in a]
+        b_str = [self.parenthesize(x, prec) for x in b]
 
         if len(b) == 0:
             return sign + '*'.join(a_str)
diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py
index aba2a6ce21..d70309a504 100644
--- a/sympy/sets/sets.py
+++ b/sympy/sets/sets.py
@@ -584,7 +584,7 @@ def _eval_Eq(self, other):
         if len(self.args) != len(other.args):
             return false
 
-        return And(*map(lambda x, y: Eq(x, y), self.args, other.args))
+        return And(*(Eq(x, y) for x, y in zip(self.args, other.args)))
 
     def _contains(self, element):
         """
@@ -1698,7 +1698,7 @@ def _eval_Eq(self, other):
         if len(self) != len(other):
             return false
 
-        return And(*map(lambda x, y: Eq(x, y), self.args, other.args))
+        return And(*(Eq(x, y) for x, y in zip(self.args, other.args)))
 
     def __iter__(self):
         return iter(self.args)
diff --git a/sympy/solvers/ode.py b/sympy/solvers/ode.py
index 29cd1edc08..4cc2f5fba4 100644
--- a/sympy/solvers/ode.py
+++ b/sympy/solvers/ode.py
@@ -2490,7 +2490,7 @@ def _recursive_walk(expr):
                         Ces.append(x)
             elif isinstance(expr, C.Integral):
                 if expr.free_symbols.issubset(Cs) and \
-                        all(map(lambda x: len(x) == 3, expr.limits)):
+                            all(len(x) == 3 for x in expr.limits):
                     Ces.append(expr)
             for i in expr.args:
                 _recursive_walk(i)
diff --git a/sympy/solvers/pde.py b/sympy/solvers/pde.py
index 7ead7a0d0f..85a4705c56 100644
--- a/sympy/solvers/pde.py
+++ b/sympy/solvers/pde.py
@@ -443,8 +443,7 @@ def checkpdesol(pde, sol, func=None, solve_for_func=True):
     # If the given solution is in the form of a list or a set
     # then return a list or set of tuples.
     if is_sequence(sol, set):
-        return type(sol)(map(lambda i: checkpdesol(pde, i,
-            solve_for_func=solve_for_func), sol))
+        return type(sol)([checkpdesol(pde, i, solve_for_func=solve_for_func) for i in sol])
 
     # Convert solution into an equation
     if not isinstance(sol, Equality):


Test patch:
diff --git a/bin/coverage_doctest.py b/bin/coverage_doctest.py
index 5f3f20f6c0..02e4c77198 100755
--- a/bin/coverage_doctest.py
+++ b/bin/coverage_doctest.py
@@ -229,7 +229,7 @@ def _get_arg_list(name, fobj):
         arg_list.append(argspec.keywords)
 
     # Truncate long arguments
-    arg_list = map(lambda x: x[:trunc], arg_list)
+    arg_list = [x[:trunc] for x in arg_list]
 
     # Construct the parameter string (enclosed in brackets)
     str_param = "%s(%s)" % (name, ', '.join(arg_list))
diff --git a/sympy/matrices/expressions/tests/test_blockmatrix.py b/sympy/matrices/expressions/tests/test_blockmatrix.py
index 75758a0c6c..e21567fa1e 100644
--- a/sympy/matrices/expressions/tests/test_blockmatrix.py
+++ b/sympy/matrices/expressions/tests/test_blockmatrix.py
@@ -97,12 +97,12 @@ def test_BlockMatrix():
 
 
 def test_BlockMatrix_trace():
-    A, B, C, D = map(lambda s: MatrixSymbol(s, 3, 3), 'ABCD')
+    A, B, C, D = [MatrixSymbol(s, 3, 3) for s in 'ABCD']
     X = BlockMatrix([[A, B], [C, D]])
     assert trace(X) == trace(A) + trace(D)
 
 def test_BlockMatrix_Determinant():
-    A, B, C, D = map(lambda s: MatrixSymbol(s, 3, 3), 'ABCD')
+    A, B, C, D = [MatrixSymbol(s, 3, 3) for s in 'ABCD']
     X = BlockMatrix([[A, B], [C, D]])
     from sympy import assuming, Q
     with assuming(Q.invertible(A)):
diff --git a/sympy/printing/tests/test_dot.py b/sympy/printing/tests/test_dot.py
index 98fc75a48a..a8921ae7e3 100644
--- a/sympy/printing/tests/test_dot.py
+++ b/sympy/printing/tests/test_dot.py
@@ -44,15 +44,15 @@ def test_dotedges():
 def test_dotprint():
     text = dotprint(x+2, repeat=False)
     assert all(e in text for e in dotedges(x+2, repeat=False))
-    assert all(n in text for n in map(lambda expr: dotnode(expr, repeat=False), (x, Integer(2), x+2)))
+    assert all(n in text for n in [dotnode(expr, repeat=False) for expr in (x, Integer(2), x+2)])
     assert 'digraph' in text
     text = dotprint(x+x**2, repeat=False)
     assert all(e in text for e in dotedges(x+x**2, repeat=False))
-    assert all(n in text for n in map(lambda expr: dotnode(expr, repeat=False), (x, Integer(2), x**2)))
+    assert all(n in text for n in [dotnode(expr, repeat=False) for expr in (x, Integer(2), x**2)])
     assert 'digraph' in text
     text = dotprint(x+x**2, repeat=True)
     assert all(e in text for e in dotedges(x+x**2, repeat=True))
-    assert all(n in text for n in map(lambda expr: dotnode(expr, pos=()), [x + x**2]))
+    assert all(n in text for n in [dotnode(expr, pos=()) for expr in [x + x**2]])
     text = dotprint(x**x, repeat=True)
     assert all(e in text for e in dotedges(x**x, repeat=True))
     assert all(n in text for n in [dotnode(x, pos=(0,)), dotnode(x, pos=(1,))])
diff --git a/sympy/printing/tests/test_latex.py b/sympy/printing/tests/test_latex.py
index c98cc8d400..b1b031df5a 100644
--- a/sympy/printing/tests/test_latex.py
+++ b/sympy/printing/tests/test_latex.py
@@ -1171,14 +1171,14 @@ def test_modifiers():
     assert latex(symbols("xDdDot")) == r"\dddot{x}"
     assert latex(symbols("xDDot")) == r"\ddot{x}"
     assert latex(symbols("xBold")) == r"\boldsymbol{x}"
-    assert latex(symbols("xnOrM")) == r"\left\|{x}\right\|"
+    assert latex(symbols("xnOrM")) == r"\left\lVert{x}\right\rVert"
     assert latex(symbols("xAVG")) == r"\left\langle{x}\right\rangle"
     assert latex(symbols("xHat")) == r"\hat{x}"
     assert latex(symbols("xDot")) == r"\dot{x}"
     assert latex(symbols("xBar")) == r"\bar{x}"
     assert latex(symbols("xVec")) == r"\vec{x}"
     assert latex(symbols("xAbs")) == r"\left|{x}\right|"
-    assert latex(symbols("xMag")) == r"\left|{x}\right|"
+    assert latex(symbols("xMag")) == r"\left\lvert{x}\right\rvert"
     assert latex(symbols("xPrM")) == r"{x}'"
     assert latex(symbols("xBM")) == r"\boldsymbol{x}"
     # Test strings that are *only* the names of modifiers
@@ -1205,7 +1205,7 @@ def test_modifiers():
     # Check a few combinations
     assert latex(symbols("xvecdot")) == r"\dot{\vec{x}}"
     assert latex(symbols("xDotVec")) == r"\vec{\dot{x}}"
-    assert latex(symbols("xHATNorm")) == r"\left\|{\hat{x}}\right\|"
+    assert latex(symbols("xHATNorm")) == r"\left\lVert{\hat{x}}\right\rVert"
     # Check a couple big, ugly combinations
     assert latex(symbols('xMathringBm_yCheckPRM__zbreveAbs')) == r"\boldsymbol{\mathring{x}}^{\left|{\breve{z}}\right|}_{{\check{y}}'}"
     assert latex(symbols('alphadothat_nVECDOT__tTildePrime')) == r"\hat{\dot{\alpha}}^{{\tilde{t}}'}_{\dot{\vec{n}}}"
diff --git a/sympy/simplify/tests/test_hyperexpand.py b/sympy/simplify/tests/test_hyperexpand.py
index 61c71c4cfd..3a2ed35276 100644
--- a/sympy/simplify/tests/test_hyperexpand.py
+++ b/sympy/simplify/tests/test_hyperexpand.py
@@ -214,7 +214,7 @@ def test_plan():
         devise_plan(Hyper_Function([2], []), Hyper_Function([S("1/2")], []), z)
 
     # We cannot use pi/(10000 + n) because polys is insanely slow.
-    a1, a2, b1 = map(lambda n: randcplx(n), range(3))
+    a1, a2, b1 = (randcplx(n) for n in range(3))
     b1 += 2*I
     h = hyper([a1, a2], [b1], z)
 
@@ -247,7 +247,7 @@ def test_plan_derivatives():
 
 
 def test_reduction_operators():
-    a1, a2, b1 = map(lambda n: randcplx(n), range(3))
+    a1, a2, b1 = (randcplx(n) for n in range(3))
     h = hyper([a1], [b1], z)
 
     assert ReduceOrder(2, 0) is None
@@ -273,7 +273,7 @@ def test_reduction_operators():
 
 
 def test_shift_operators():
-    a1, a2, b1, b2, b3 = map(lambda n: randcplx(n), range(5))
+    a1, a2, b1, b2, b3 = (randcplx(n) for n in range(5))
     h = hyper((a1, a2), (b1, b2, b3), z)
 
     raises(ValueError, lambda: ShiftA(0))
@@ -287,7 +287,7 @@ def test_shift_operators():
 
 
 def test_ushift_operators():
-    a1, a2, b1, b2, b3 = map(lambda n: randcplx(n), range(5))
+    a1, a2, b1, b2, b3 = (randcplx(n) for n in range(5))
     h = hyper((a1, a2), (b1, b2, b3), z)
 
     raises(ValueError, lambda: UnShiftA((1,), (), 0, z))
@@ -435,9 +435,9 @@ def test_meijerg():
     # carefully set up the parameters.
     # NOTE: this used to fail sometimes. I believe it is fixed, but if you
     #       hit an inexplicable test failure here, please let me know the seed.
-    a1, a2 = map(lambda n: randcplx() - 5*I - n*I, range(2))
-    b1, b2 = map(lambda n: randcplx() + 5*I + n*I, range(2))
-    b3, b4, b5, a3, a4, a5 = map(lambda n: randcplx(), range(6))
+    a1, a2 = (randcplx(n) - 5*I - n*I for n in range(2))
+    b1, b2 = (randcplx(n) + 5*I + n*I for n in range(2))
+    b3, b4, b5, a3, a4, a5 = (randcplx() for n in range(6))
     g = meijerg([a1], [a3, a4], [b1], [b3, b4], z)
 
     assert ReduceOrder.meijer_minus(3, 4) is None
@@ -471,8 +471,7 @@ def test_meijerg():
 
 def test_meijerg_shift_operators():
     # carefully set up the parameters. XXX this still fails sometimes
-    a1, a2, a3, a4, a5, b1, b2, b3, b4, b5 = \
-        map(lambda n: randcplx(n), range(10))
+    a1, a2, a3, a4, a5, b1, b2, b3, b4, b5 = (randcplx(n) for n in range(10))
     g = meijerg([a1], [a3, a4], [b1], [b3, b4], z)
 
     assert tn(MeijerShiftA(b1).apply(g, op),
@@ -588,7 +587,7 @@ def test_lerchphi():
 
 def test_partial_simp():
     # First test that hypergeometric function formulae work.
-    a, b, c, d, e = map(lambda _: randcplx(), range(5))
+    a, b, c, d, e = (randcplx() for _ in range(5))
     for func in [Hyper_Function([a, b, c], [d, e]),
             Hyper_Function([], [a, b, c, d, e])]:
         f = build_hypergeometric_formula(func)