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
  How to remove unwanted images and tables from a Word file using Python? rownong 2 756 Feb-04-2025, 08:30 AM
Last Post: Pedroski55
  Word matching with specific parameters CascadeDiver 3 876 Jan-28-2025, 02:10 PM
Last Post: perfringo
  word guessing game, hints STUdevil 1 1,610 Oct-12-2024, 01:53 AM
Last Post: menator01
  word game, how to give hints STUdevil 5 1,550 Oct-07-2024, 06:20 PM
Last Post: STUdevil
  Retrieve word from string knob 4 1,553 Jan-22-2024, 06:40 PM
Last Post: Pedroski55
  How to create a table with different sizes of columns in MS word pepe 8 7,634 Dec-08-2023, 07:31 PM
Last Post: Pedroski55
  extract substring from a string before a word !! evilcode1 3 1,848 Nov-08-2023, 12:18 AM
Last Post: evilcode1
  Replace a text/word in docx file using Python Devan 4 21,188 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 1,502 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 1,637 Sep-22-2023, 02:33 PM
Last Post: carecavoador

Forum Jump:

User Panel Messages

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