'How to Sort an Appended List In an if Statement in Python?
I have these blocks of codes here.
When you enter an input, the input is supposed to be sorted alphabetically to the existing list.
However, my input keeps going to the bottom of the list. I have been at this for 2 hours and can't even remember anymore what I have tried. My apologies. This is my first post here. Below are the codes:
names = ['Anna', 'Faizal', 'Fylvia', 'Karl', 'Maria', 'Matt']
for i in names:
print(i)
print('Enter a new name')
newNames = input()
if newNames == names.append(newNames) == newList:
newList.sort()
print(newList)
else:
newNames == ' '
print('\n'.join(names))
Solution 1:[1]
There's lots of confusing, unnecessary code. Just append the new name to the list and then sort it.
names = ['Anna', 'Faizal', 'Fylvia', 'Karl', 'Maria', 'Matt']
print('\n'.join(names))
newname = input('Enter a new name: ')
names.append(newname)
names.sort()
print('\n'.join(names))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Barmar |
