Skip to content

Commit

Permalink
gh-38697: fixes for ruff warning C416
Browse files Browse the repository at this point in the history
    
this fixes almost every C416 warning from `ruff`

Unnecessary `list` comprehension (rewrite using `list()`)

### 📝 Checklist

- [x] The title is concise and informative.
- [x] The description explains in detail what this PR is about.
- [ ] I have linked a relevant issue or discussion.
- [ ] I have created tests covering the changes.
- [ ] I have updated the documentation and checked the documentation
preview.
    
URL: #38697
Reported by: Frédéric Chapoton
Reviewer(s): David Coudert, Frédéric Chapoton
  • Loading branch information
Release Manager committed Sep 27, 2024
2 parents e452a39 + cb73962 commit 7721e53
Show file tree
Hide file tree
Showing 26 changed files with 62 additions and 64 deletions.
4 changes: 2 additions & 2 deletions src/sage/crypto/mq/sr.py
Original file line number Diff line number Diff line change
Expand Up @@ -2214,9 +2214,9 @@ def antiphi(self, l):
True
"""
if isinstance(l, Matrix):
ret = [e for e in l.transpose().list()[0:-1:self.e]]
ret = l.transpose().list()[0:-1:self.e]
else:
ret = [e for e in l[0:-1:self.e]]
ret = l[0:-1:self.e]

if isinstance(l, list):
return ret
Expand Down
2 changes: 1 addition & 1 deletion src/sage/databases/findstat.py
Original file line number Diff line number Diff line change
Expand Up @@ -2211,7 +2211,7 @@ def _fetch_data(self):

included = _get_json(url)["included"]
# slightly simplify the representation
data = {key: val for key, val in included["Statistics"][self.id_str()].items()}
data = dict(included["Statistics"][self.id_str()].items())
# we replace the list of identifiers in Bibliography with the dictionary
data["Bibliography"] = included["References"]
return data
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1387,7 +1387,7 @@ def order_p_automorphisms(rational_function, pre_image):
if case == 'fix':
T = [x[0] for x in pre_image]
elif case == 'F-pre_images':
T = [x for x in pre_image[0][1]]
T = list(pre_image[0][1])
else:
T = []

Expand All @@ -1396,19 +1396,19 @@ def order_p_automorphisms(rational_function, pre_image):
pt = guy[0]
# treat case of multiple F-rational fixed points or
# 1 F-rational fixed point with F-rational pre-images
if T != []:
if T:
M = [t for t in T if t != pt]
m = len(M)
if pt == [F(1),F(0)]:
if pt == [F(1), F(0)]:
for i in range(1, m):
s = z + M[i][0] - M[0][0]
if s(phi(z)) == phi(s(z)):
automorphisms_p.append(s)
else:
u = F(1) / (z - pt[0])
u_inv = pt[0] + F(1)/z
for i in range(1,m):
if M[0] == [F(1),F(0)]:
for i in range(1, m):
if M[0] == [F(1), F(0)]:
uy1 = 0
else:
uy1 = u(M[0][0])
Expand Down
2 changes: 1 addition & 1 deletion src/sage/geometry/cone.py
Original file line number Diff line number Diff line change
Expand Up @@ -2603,7 +2603,7 @@ def ConeFace(atoms, facets):
faces.append(self)
for face in dfaces:
L.add_edge(face_to_index[face], next_index)
D = {i:f for i,f in enumerate(faces)}
D = dict(enumerate(faces))
L.relabel(D)
self._face_lattice = FinitePoset(L, faces, key=id(self))
return self._face_lattice
Expand Down
2 changes: 1 addition & 1 deletion src/sage/geometry/fan.py
Original file line number Diff line number Diff line change
Expand Up @@ -1516,7 +1516,7 @@ def FanFace(rays, cones):
# ray incidence information to the total list, it would be
# confused with the generating cone in the case of a single cone.
elements[labels[0]] = FanFace(tuple(range(self.nrays())), ())
D = {i: f for i, f in enumerate(elements)}
D = dict(enumerate(elements))
L.relabel(D)
self._cone_lattice = FinitePoset(L, elements, key=id(self))

Expand Down
2 changes: 1 addition & 1 deletion src/sage/geometry/hasse_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,6 @@ def default_face_constructor(atoms, coatoms, **kwds):
atoms, coatoms = face
elements[labels[index]] = face_constructor(
tuple(sorted(atoms)), tuple(sorted(coatoms)), **kwds)
D = {i: f for i, f in enumerate(elements)}
D = dict(enumerate(elements))
L.relabel(D)
return FiniteLatticePoset(L, elements, key=key)
2 changes: 1 addition & 1 deletion src/sage/geometry/lattice_polytope.py
Original file line number Diff line number Diff line change
Expand Up @@ -2064,7 +2064,7 @@ def LPFace(vertices, facets):
faces.append(self)
for face in dfaces:
L.add_edge(face_to_index[face], next_index)
D = {i:f for i,f in enumerate(faces)}
D = dict(enumerate(faces))
L.relabel(D)
return FinitePoset(L, faces, key=id(self))

Expand Down
2 changes: 1 addition & 1 deletion src/sage/geometry/linear_expression.py
Original file line number Diff line number Diff line change
Expand Up @@ -500,7 +500,7 @@ def basis(self):
"""
from sage.sets.family import Family
gens = self.gens()
d = {i: g for i, g in enumerate(gens)}
d = dict(enumerate(gens))
d['b'] = self.element_class(self, self.ambient_module().zero(),
self.base_ring().one())
return Family(list(range(len(gens))) + ['b'], lambda i: d[i])
Expand Down
4 changes: 2 additions & 2 deletions src/sage/geometry/polyhedron/backend_normaliz.py
Original file line number Diff line number Diff line change
Expand Up @@ -807,7 +807,7 @@ def rays_subspace_lattice_ieqs_QQ(vertices, rays, lines, ieqs):

from sage.matrix.constructor import Matrix
lattice = Matrix(ZZ, nmz_vertices + nmz_rays + nmz_lines).saturation()
nmz_lattice = [[x for x in y] for y in lattice]
nmz_lattice = [list(y) for y in lattice]

if Matrix(ZZ, nmz_vertices + nmz_rays).rank() == Matrix(ZZ, nmz_rays).rank() + 1:
# The recession cone is full-dimensional.
Expand Down Expand Up @@ -2300,7 +2300,7 @@ class functions.
# A check on whether the character table has permuted columns
tbl = G_perm_gap.CharacterTable()
perm = tbl.IdentificationOfConjugacyClasses()
ident_perm = [i for i in range(1, 1 + n_classes)]
ident_perm = list(range(1, 1 + n_classes))
assert perm == ident_perm, "The conjugacy classes don't match with the character table"

# Create fixed subpolytopes and their Ehrhart series
Expand Down
2 changes: 1 addition & 1 deletion src/sage/geometry/polyhedron/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -584,7 +584,7 @@ def is_inscribed(self, certificate=False):
for vertex in affine_basis:
vertex_vector = vertex.vector()
raw_data += [[sum(i**2 for i in vertex_vector)] +
[i for i in vertex_vector] + [1]]
list(vertex_vector) + [1]]
matrix_data = matrix(raw_data)

# The determinant "a" should not be zero because
Expand Down
8 changes: 4 additions & 4 deletions src/sage/geometry/polyhedron/plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -769,7 +769,7 @@ def _init_area_2d(self, polyhedron):
[[3, 0, 1, 2]]
"""
assert polyhedron.ambient_dim() == 2, "Requires polyhedron in 2d"
vertices = [v for v in polyhedron.Vrep_generator()]
vertices = list(polyhedron.Vrep_generator())
vertices = cyclic_sort_vertices_2d(vertices)
coords = []

Expand Down Expand Up @@ -802,7 +802,7 @@ def adjacent_vertices(i):
coords[i] + shift, coords[i - 1] + shift])

if polyhedron.n_lines() == 2:
[line1, line2] = [l for l in polyhedron.lines()]
line1, line2 = polyhedron.lines()
assert len(coords) == 1, "Can have only a single vertex!"
v = coords[0]
l1 = line1()
Expand Down Expand Up @@ -848,7 +848,7 @@ def defining_equation(): # corresponding to a polygon
faces = []
face_inequalities = []
for facet_equation in defining_equation():
vertices = [v for v in facet_equation.incident()]
vertices = list(facet_equation.incident())
face_inequalities.append(facet_equation)
vertices = cyclic_sort_vertices_2d(vertices)
if len(vertices) >= 3:
Expand Down Expand Up @@ -894,7 +894,7 @@ def adjacent_vertices(i):
coords[1] + shift, coords[0] + shift])

if polyhedron.n_lines() == 2:
[line1, line2] = [l for l in polyhedron.line_generator()]
line1, line2 = polyhedron.line_generator()
l1 = line1()
l2 = line2()
for v in polyhedron.vertex_generator():
Expand Down
4 changes: 2 additions & 2 deletions src/sage/graphs/digraph.py
Original file line number Diff line number Diff line change
Expand Up @@ -1318,7 +1318,7 @@ def in_degree(self, vertices=None, labels=False):
if vertices in self:
return self._backend.in_degree(vertices)
elif labels:
return {v: d for v, d in self.in_degree_iterator(vertices, labels=labels)}
return dict(self.in_degree_iterator(vertices, labels=labels))
return list(self.in_degree_iterator(vertices, labels=labels))

def in_degree_iterator(self, vertices=None, labels=False):
Expand Down Expand Up @@ -1388,7 +1388,7 @@ def out_degree(self, vertices=None, labels=False):
if vertices in self:
return self._backend.out_degree(vertices)
elif labels:
return {v: d for v, d in self.out_degree_iterator(vertices, labels=labels)}
return dict(self.out_degree_iterator(vertices, labels=labels))
return list(self.out_degree_iterator(vertices, labels=labels))

def out_degree_iterator(self, vertices=None, labels=False):
Expand Down
2 changes: 1 addition & 1 deletion src/sage/graphs/digraph_generators.py
Original file line number Diff line number Diff line change
Expand Up @@ -1307,7 +1307,7 @@ def Kautz(self, k, D, vertices='strings'):
raise ValueError("degree must be greater than or equal to one")

# We start building the set of vertices
V = [i for i in my_alphabet]
V = list(my_alphabet)
for i in range(D - 1):
VV = []
for w in V:
Expand Down
2 changes: 1 addition & 1 deletion src/sage/graphs/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -5965,7 +5965,7 @@ def twograph(self):
T.append([x, y, z])

T = TwoGraph(T)
T.relabel({i: v for i, v in enumerate(self)})
T.relabel(dict(enumerate(self)))

return T

Expand Down
2 changes: 1 addition & 1 deletion src/sage/graphs/graph_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -1491,7 +1491,7 @@ def layout_tree(self, root, orientation):
children = {root: T.neighbors(root)}

# Always make a copy of the children because they get eaten
stack = [[u for u in children[root]]]
stack = [list(children[root])]
stick = [root]
parent = {u: root for u in children[root]}
pos = {}
Expand Down
5 changes: 3 additions & 2 deletions src/sage/interacts/library.py
Original file line number Diff line number Diff line change
Expand Up @@ -1464,12 +1464,13 @@ def riemann_sum(
b = interval_g[0][1]
func = symbolic_expression(f).function(x)
division = [a]+[a+random()*(b-a) for i in range(n-1)]+[b]
division = sorted([i for i in division])
division = sorted(division)
xs = [division[i]+random()*(division[i+1]-division[i]) for i in range(n)]
ys = [func(x_val) for x_val in xs]
rects = Graphics()
for i in range(n):
body = [[division[i],0],[division[i],ys[i]],[division[i+1],ys[i]],[division[i+1],0]]
body = [[division[i], 0], [division[i], ys[i]],
[division[i+1], ys[i]], [division[i+1], 0]]
if ys[i].n() > 0:
color_rect = 'green'
else:
Expand Down
2 changes: 1 addition & 1 deletion src/sage/interfaces/fricas.py
Original file line number Diff line number Diff line change
Expand Up @@ -1963,7 +1963,7 @@ def _sage_(self):

if head == "Factored":
l = P.new('[[f.factor, f.exponent] for f in factors(%s)]' % self._name).sage()
return Factorization([(p, e) for p, e in l])
return Factorization(list(l))

if head == "UnivariatePolynomial":
base_ring = self._get_sage_type(domain[2])
Expand Down
6 changes: 3 additions & 3 deletions src/sage/interfaces/kenzo.py
Original file line number Diff line number Diff line change
Expand Up @@ -437,10 +437,10 @@ def homology(self, n):
m1 = __chcm_mat__(echcm1, n)
m2 = __chcm_mat__(echcm1, n + 1)
homology = __homologie__(m1, m2)
lhomomology = [i for i in EclListIterator(homology)]
lhomomology = list(EclListIterator(homology))
res = []
for component in lhomomology:
pair = [i for i in EclListIterator(component)]
pair = list(EclListIterator(component))
res.append(pair[0].python())
return HomologyGroup(len(res), ZZ, res)

Expand Down Expand Up @@ -1309,7 +1309,7 @@ def SFiniteSimplicialSet(ksimpset, limit):
bases.append(lbasis_k)
names.append(names_k)
all_simplices = __sfinitesimplicialset_aux1__(ksimpset._kenzo, limit)
lall_simplices = [i for i in EclListIterator(all_simplices)]
lall_simplices = list(EclListIterator(all_simplices))
dim = 1
for Kdim in lall_simplices:
for simp in Kdim:
Expand Down
10 changes: 5 additions & 5 deletions src/sage/manifolds/differentiable/degenerate_submanifold.py
Original file line number Diff line number Diff line change
Expand Up @@ -452,12 +452,12 @@ def set_transverse(self, rigging=None, normal=None):
sage: S.set_transverse(rigging=t)
"""
if isinstance(rigging, (list, tuple)):
rigging = [elt for elt in rigging]
rigging = list(rigging)
else:
if rigging is not None:
rigging = [rigging]
if isinstance(normal, (list, tuple)):
normal = [elt for elt in normal]
normal = list(normal)
else:
if normal is not None:
normal = [normal]
Expand Down Expand Up @@ -540,11 +540,11 @@ def screen(self, name, screen, rad, latex_name=None):
Lorentzian manifold M
"""
if isinstance(screen, (list, tuple)):
screen = [elt for elt in screen]
screen = list(screen)
else:
screen = [screen]
if isinstance(rad, (list, tuple)):
rad = [elt for elt in rad]
rad = list(rad)
else:
rad = [rad]
if name in self._screens:
Expand Down Expand Up @@ -1288,7 +1288,7 @@ def principal_directions(self, screen=None):
for eigen_vector in eigen_space[1]:
v = self._ambient.vector_field(name="e_{}".format(next(counter))
).along(self.immersion())
v[frame, :] = [elt for elt in eigen_vector] + [0]
v[frame, :] = list(eigen_vector) + [0]
res.append((TangentTensor(v, self.immersion()), self.scalar_field(
{chart: eigen_space[0] for chart in self.top_charts()})))
#res[-1][0].set_name("e_{}".format(next(counter)))
Expand Down
4 changes: 2 additions & 2 deletions src/sage/manifolds/differentiable/diff_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -1024,8 +1024,8 @@ def _pullback_chart(diff_map, tensor, chart1, chart2):
if nproc != 1:
# Parallel computation
lol = lambda lst, sz: [lst[i:i+sz] for i in range(0, len(lst), sz)]
ind_list = [ind for ind in ptcomp.non_redundant_index_generator()]
ind_step = max(1, int(len(ind_list)/nproc/2))
ind_list = list(ptcomp.non_redundant_index_generator())
ind_step = max(1, (len(ind_list) // nproc) // 2)
local_list = lol(ind_list, ind_step)
# list of input parameters
listParalInput = [(tcomp, chart1, chart2, coord2_1, jacob,
Expand Down
2 changes: 1 addition & 1 deletion src/sage/manifolds/differentiable/integrated_curve.py
Original file line number Diff line number Diff line change
Expand Up @@ -1066,7 +1066,7 @@ def solve(self, step=None, method='odeint', solution_key=None,
t_min = self.domain().lower_bound()
t_max = self.domain().upper_bound()

eqns_num = [eq for eq in self._equations_rhs]
eqns_num = list(self._equations_rhs)
# 'self._equations_rhs' needs not to be modified ever, because we
# want to keep track of the most general form of the equations
# defining self, since those may contain parameters (which, for
Expand Down
6 changes: 3 additions & 3 deletions src/sage/manifolds/differentiable/tensorfield_paral.py
Original file line number Diff line number Diff line change
Expand Up @@ -1414,12 +1414,12 @@ def lie_derivative(self, vector):

# get n processes
nproc = Parallelism().get('tensor')
if nproc != 1 :
if nproc != 1:

# Parallel computation
lol = lambda lst, sz: [lst[i:i+sz] for i in range(0, len(lst), sz)]
ind_list = [ind for ind in resc.non_redundant_index_generator()]
ind_step = max(1, int(len(ind_list)/nproc))
ind_list = list(resc.non_redundant_index_generator())
ind_step = max(1, len(ind_list) // nproc)
local_list = lol(ind_list, ind_step)
# list of input parameters:
listParalInput = [(self, vector, coord_frame, chart, ind_part) for ind_part in local_list]
Expand Down
4 changes: 2 additions & 2 deletions src/sage/numerical/optimize.py
Original file line number Diff line number Diff line change
Expand Up @@ -740,7 +740,7 @@ def error_function(params, x_data, y_data):
estimated_params = estimated_params.tolist()

if solution_dict:
return {i0: i1 for i0, i1 in zip(parameters, estimated_params)}
return dict(zip(parameters, estimated_params))

return [item[0] == item[1] for item in zip(parameters, estimated_params)]

Expand Down Expand Up @@ -859,7 +859,7 @@ def binpacking(items, maximum=1, k=None, solver=None, verbose=0,
TypeError: parameter items must be a list or a dictionary.
"""
if isinstance(items, list):
weight = {i:w for i,w in enumerate(items)}
weight = dict(enumerate(items))
elif isinstance(items, dict):
weight = items
else:
Expand Down
Loading

0 comments on commit 7721e53

Please sign in to comment.