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
  search for more than one word using lambda illmattic 2 160 Nov-13-2020, 11:44 AM
Last Post: illmattic
  Mail Merge from DataFrame into Word Label Template PEGylated_User 0 83 Nov-10-2020, 01:01 PM
Last Post: PEGylated_User
  Searching for specific word in text files. JellyCreeper6 1 132 Nov-03-2020, 01:52 PM
Last Post: DeaD_EyE
  I try to import data from Excel table to Word Template. NewbiePyPy 0 129 Oct-21-2020, 12:25 PM
Last Post: NewbiePyPy
  Recognising mathematical expressions from word and pdf file Preeti15 0 242 Aug-19-2020, 09:06 AM
Last Post: Preeti15
  The 'b' Word Harshil 5 468 Aug-12-2020, 03:56 PM
Last Post: Harshil
  Iterating over word vs. character Mark17 6 319 Aug-11-2020, 04:56 PM
Last Post: Mark17
  Trying to find first 2 letter word in a list of words Oldman45 7 439 Aug-11-2020, 08:59 AM
Last Post: Oldman45
  How to extract a single word from a text file buttercup 7 487 Jul-22-2020, 04:45 AM
Last Post: bowlofred
  Complex word search multiple files Kristenl2784 0 248 Jul-18-2020, 01:22 PM
Last Post: Kristenl2784

Forum Jump:

User Panel Messages

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