-5

So I'm kinda new to python and was given a problem as follows: Given the list names , find the largest element in the list and swap it with the last element. For example, the list ["Carlton", "Quincy" "Adam", "Bernard"] would become ["Carlton", "Bernard", "Adam", "Quincy"] . Assume names is not empty

I thought about doing list Comprehension but I don't know how I would write that out in code

EDIT: Largest in this case would be the length of the string (sorry for not clarifying!!!))

user3685810
  • 3
  • 1
  • 3

2 Answers2

1

If by largest, you mean longest, then you could iterate over the list to find the longest name, and then swap them.

maxLen = 0
maxI = 0
for i in range(0, len(names)):
  if len(names[i]) > maxLen:
      maxLen = len(names[i])
      maxI = i

temp = names[-1]
names[-1] = names[maxI]
names[maxI] = temp

This is an overly convoluted way of doing it, but it's so drawn out to make it more obvious as to what's going on. With that said, you really should be more specific about what "largest" means.

Noah
  • 93
  • 5
1
names = [foo, fooooo, bar, baaar]
a, b = i.index(max(name, key=len)), -1
i[b], i[a] = i[a], i[b]

Courtesy of this.

Community
  • 1
  • 1
user2963623
  • 2,267
  • 1
  • 14
  • 25