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
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)
word = ['xyz', 'dsddf', 'sdfs']
for w in word:
  if len(w) > 3:
      word.insert(0, w) 

for w in word: 
for w in word[:]:
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.
got it...!!
Thanks Dear!!

Possibly Related Threads…
Thread Author Replies Views Last Post
  Docx Convert Word Header to Body CaptainCsaba 3 369 Jun-02-2021, 01:25 PM
Last Post: Larz60+
  –°ombine (Merge) word documents using python-docx Lancellot 1 2,369 May-12-2021, 11:07 AM
Last Post: toothedsword
  remove vowels in word with conditional ambrozote 12 681 May-02-2021, 06:57 PM
Last Post: perfringo
  How to read check boxes from word document srikanthpython 0 377 Mar-30-2021, 01:58 PM
Last Post: srikanthpython
  looping wordlist keeps repeating when word not found OTH 1 445 Feb-24-2021, 05:36 PM
Last Post: nilamo
Thumbs Down extracting data/strings from Word doc mikkelibsen 1 443 Feb-10-2021, 11:06 AM
Last Post: Larz60+
Question Word, adding a hyperlink from a bookmark using Python mart79 1 468 Jan-14-2021, 08:41 PM
Last Post: Larz60+
  Trying to get the first letter of every word in a list DanielCook 2 528 Jan-05-2021, 05:06 PM
Last Post: deanhystad
  [GoogleTrans] How can i print my translation word ?... JamieVanCadsand 6 7,943 Dec-23-2020, 04:38 PM
Last Post: shyamkumardr
  How to make a telegram bot respond to the specific word in a sentence? Metodolog 2 2,133 Dec-22-2020, 07:30 AM
Last Post: martabassof

Forum Jump:

User Panel Messages

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