Python Forum
Reverse list items in a stupid way
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Reverse list items in a stupid way
#1
Why is the following code not working?

text="I am very busy today"
a=text.split()
word=a
print(word)
word[4]=a[0]
word[3]=a[1]
word[2]=a[2]
word[1]=a[3]
word[0]=a[4]
print(word)
I get this answer which is wrong:
['I', 'am', 'very', 'busy', 'today']
['I', 'am', 'very', 'am', 'I']

I know I can do it easily with the following but I really want to know why the above code failed:
text="I am very busy today"
a=text.split()
a[::-1]
Thanks for your help.
Reply
#2
Lists are mutable, and are therefore copied and passed by reference. 'a' is not a list, it is a pointer to a list. word = a copies the pointer not the list. So everything you do to word you do to a, and vice versa. You need to copy the list pointed to by a, with something like word = a[:]. Or just make a new list, word = [''] * len(a), since you are overwriting everything in word anyway.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
I wasn't aware of the pointer to a list thing. Thanks for the explanation.
Reply
#4
This is a nice information video on youtube
Reply
#5
(Jul-28-2019, 08:45 AM)ThomasL Wrote: This is a nice information video on youtube

Thanks for the link but what he explained is not applicable to my scenario.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Why do I have to repeat items in list slices in order to make this work? Pythonica 7 1,950 May-22-2023, 10:39 PM
Last Post: ICanIBB
  Finding combinations of list of items (30 or so) LynnS 1 1,166 Jan-25-2023, 02:57 PM
Last Post: deanhystad
  For Word, Count in List (Counts.Items()) new_coder_231013 6 3,819 Jul-21-2022, 02:51 PM
Last Post: new_coder_231013
  How to get list of exactly 10 items? Mark17 1 2,982 May-26-2022, 01:37 PM
Last Post: Mark17
  how to assign items from a list to a dictionary CompleteNewb 3 1,993 Mar-19-2022, 01:25 AM
Last Post: deanhystad
  Reading list items without brackets and quotes jesse68 6 5,436 Jan-14-2022, 07:07 PM
Last Post: jesse68
Question How to gather specific second-level items from a list chatguy 2 1,859 Dec-17-2021, 05:05 PM
Last Post: chatguy
  Question about List.reverse() method tomliuwhite 1 1,671 Dec-07-2021, 08:20 AM
Last Post: ndc85430
  deleting select items from a list Skaperen 13 5,415 Oct-11-2021, 01:02 AM
Last Post: Skaperen
  Getting All Items From A List knight2000 4 2,704 Sep-25-2021, 12:56 AM
Last Post: knight2000

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020