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.
Reply
#3
got it...!!
Thanks Dear!!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  search for more than one word using lambda illmattic 2 171 Nov-13-2020, 11:44 AM
Last Post: illmattic
  Mail Merge from DataFrame into Word Label Template PEGylated_User 0 91 Nov-10-2020, 01:01 PM
Last Post: PEGylated_User
  Searching for specific word in text files. JellyCreeper6 1 140 Nov-03-2020, 01:52 PM
Last Post: DeaD_EyE
  I try to import data from Excel table to Word Template. NewbiePyPy 0 136 Oct-21-2020, 12:25 PM
Last Post: NewbiePyPy
  Recognising mathematical expressions from word and pdf file Preeti15 0 250 Aug-19-2020, 09:06 AM
Last Post: Preeti15
  The 'b' Word Harshil 5 475 Aug-12-2020, 03:56 PM
Last Post: Harshil
  Iterating over word vs. character Mark17 6 323 Aug-11-2020, 04:56 PM
Last Post: Mark17
  Trying to find first 2 letter word in a list of words Oldman45 7 442 Aug-11-2020, 08:59 AM
Last Post: Oldman45
  How to extract a single word from a text file buttercup 7 492 Jul-22-2020, 04:45 AM
Last Post: bowlofred
  Complex word search multiple files Kristenl2784 0 251 Jul-18-2020, 01:22 PM
Last Post: Kristenl2784

Forum Jump:

User Panel Messages

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