Python Forum
difference between word: and word[:] in for loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
difference between word: and word[:] in for loop
#1
Hi Friends, I have some confusion in python kindly help me. What is difference between these two statements
 
word = ['xyz', 'dsddf', 'sdfs'] 
for w in word:
    if len(w) > 3:
       word.insert(0, w)
and
word = ['xyz', 'dsddf', 'sdfs']
for w in word:
  if len(w) > 3:
      word.insert(0, w) 

 
for w in word: 
VS
for w in word[:]:
??
Reply
#2
It is called slicing. Without any numbers however it just returns a shallow copy of the object instead. So you are looping a shallow copy of the object word instead of actual object word.

You should always loop over a copy of the object if you are modifying that object in that same loop. Other wise you can have problems. If you have nested lists inside your list..then you will need a deep copy.
Recommended Tutorials:
Reply
#3
got it...!!
Thanks Dear!!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Retrieve word from string knob 4 431 Jan-22-2024, 06:40 PM
Last Post: Pedroski55
  How to create a table with different sizes of columns in MS word pepe 8 1,412 Dec-08-2023, 07:31 PM
Last Post: Pedroski55
  extract substring from a string before a word !! evilcode1 3 491 Nov-08-2023, 12:18 AM
Last Post: evilcode1
  Replace a text/word in docx file using Python Devan 4 2,840 Oct-17-2023, 06:03 PM
Last Post: Devan
  How to summarize an article that is stored in a word document on your laptop? Mikedicenso87 2 612 Oct-06-2023, 12:07 PM
Last Post: Mikedicenso87
Thumbs Up Convert word into pdf and copy table to outlook body in a prescribed format email2kmahe 1 704 Sep-22-2023, 02:33 PM
Last Post: carecavoador
  Guess the word game help jackthechampion 3 2,957 Sep-06-2023, 06:51 AM
Last Post: Pedroski55
  Automate Word snippets PHbench 0 518 Jun-06-2023, 06:59 PM
Last Post: PHbench
  Word documents merging crewdk 1 811 Apr-03-2023, 06:32 AM
Last Post: buran
  Help replacing word in Mutiple files. (SOLVED) mm309d 0 795 Mar-21-2023, 03:43 AM
Last Post: mm309d

Forum Jump:

User Panel Messages

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