user9654395
user9654395

Reputation: 109

Can I do it that code just one "1-dim array"?

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

Answers (2)

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

StardustGogeta
StardustGogeta

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

Related Questions