0

I have a list J consisting of lists. I am trying to sort elements of each list in ascending order. I present the current and expected outputs.

J=[[10, 4, 7], [10, 4],[1,9,8]]
for i in range(0,len(J)):
    J[0].sort()

The current output is

[[4, 7, 10], [10, 4], [1, 9, 8]]

The expected output is

[[4, 7, 10], [4, 10], [1, 8, 9]]
6
  • 3
    Close, but try: J[i].sort() inside the loop rather than J[0].sort(). Commented Jul 31, 2022 at 8:47
  • You are sorting J[0] i times. Commented Jul 31, 2022 at 8:47
  • Use the object directly in the loop to avoid this confusion: for li in J: li.sort() Commented Jul 31, 2022 at 8:49
  • Try, either [sorted(l) for l in J] or [l for l in J if l.sort() is None]. Check the following URL for more details: docs.python.org/3/howto/sorting.html Commented Jul 31, 2022 at 8:57
  • @RaviJoshi The second example is very non-idiomatic and confusing. List comprehensions should not be abused for a side effect Commented Jul 31, 2022 at 9:31

1 Answer 1

1

Just remove the range

J=[[10, 4, 7], [10, 4],[1,9,8]]
for i in J:
    i.sort()
print(J)

Output:

[[4, 7, 10], [4, 10], [1, 8, 9]]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.