Reputation: 109
I have this code;
list = ["Python", "is", "good", "program"]
newlist = []
for i in range(1, len(list)+1):
newlist.append(list[-i])
print newlist
and output ;
['program', 'good', 'is', 'python']
so code's goal is reversing words by words. But I did this code with new list. Can I do it just one list? I mean just "list", without "newlist" ..
edit: I forget to say, Built-in functions or any ready code are not acceptable because of my school. please your helping related be my code.
Upvotes: 1
Views: 39
Reputation: 977
You want to swap it in place then. Something like this should do.
colors = ["red", "green", "blue", "purple"];
for i in range(len(colors) // 2):
color = colors[i]
colors[i] = colors[len(colors) - 1 - i]
colors[len(colors) - 1 - i] = color
print(colors)
Upvotes: 1
Reputation: 3406
The following code should work:
ls = ["Python", "is", "good", "program"]
for x in range(len(ls)):
ls.insert(x, ls.pop().lower())
print(ls)
# ['program', 'good', 'is', 'python']
It turns every word to lowercase as it iterates through. As an aside, I would not recommend using the reserved list
keyword.
Upvotes: 0