The input in the array list is not completely reversed and it just filters only two when using FOR loop

Viewed 58
tweet=['hi','hope','hippo','bow']
temp=[]
for i in tweet:
    temp.append(tweet.pop())           
print(temp) 

Am trying to reverse the string but using FOR loop it prints out only BOW and HIPPO , if i use WHILE loop it is perfect. Help me solve this?

3 Answers

Because pop on tweet affects your loop iterator.
You can easily prevent this by shallow copying(tweet[:]):

tweet = ['hi', 'hope', 'hippo', 'bow']
temp = []
for i in tweet[:]:
    temp.append(tweet.pop())
print(temp)

output:

['bow', 'hippo', 'hope', 'hi']

By the way, you can reverse a list by builtin function reversed:

tweet = ['hi', 'hope', 'hippo', 'bow']
temp = list(reversed(tweet))
print(temp)

output:

['bow', 'hippo', 'hope', 'hi']

Or, you can use slicing(answered by @Ch3steR):

tweet = ['hi', 'hope', 'hippo', 'bow']
temp = tweet[::-1]
print(temp)

As already pointed there exist built-in reversed function for that task, but I want to point one thing. In your code you do for i in tweet: but then do not use that i, so basically you are doing same action independently from current element, thus you might use for _ in range(len(tweet)) to execute it n times, where n is number of elements (length) of tweet following way:

tweet=['hi','hope','hippo','bow']
temp=[]
for _ in range(len(tweet)):
    temp.append(tweet.pop())           
print(temp)

Output:

['bow', 'hippo', 'hope', 'hi']

_ by convention denotes variable which I do not care about.

you can use the built-in function reversed:

print(*reversed(tweet))

output:

bow hippo hope hi

the issue with your code it is because you are changing the size of your tweet while you are iterating over in a for loop

if you want to use a for loop:

tweet=['hi','hope','hippo','bow']
temp=[]
for e in tweet[::-1]:
    temp.append(e)           
print(temp) 
Related