Bottom Page

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[:]:
??
Quote
#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.
Skaperen and zowhair like this post
Quote
#3
got it...!!
Thanks Dear!!
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Remove a sentence if it contains a word. lokhtar 6 192 Feb-11-2020, 04:43 PM
Last Post: stullis
  is there a way: repeat key word args Skaperen 2 161 Feb-03-2020, 06:03 PM
Last Post: Skaperen
  filter just with the string word jacklee26 2 297 Feb-03-2020, 03:25 PM
Last Post: snippsat
  Bulk Generating Cloze Deletions based on Tatoeba sentences and word frequency lists wizzie 10 395 Dec-23-2019, 12:16 PM
Last Post: wizzie
  Reverse the string word sneha 2 317 Dec-12-2019, 03:37 AM
Last Post: sneha
  How to make a telegram bot respond to the specific word in a sentence? Metodolog 1 151 Dec-02-2019, 11:19 PM
Last Post: stullis
  Problem with a language word problem baobei 16 1,715 Nov-23-2019, 12:26 AM
Last Post: baobei
  problem a with a word question baobei 5 949 Nov-22-2019, 05:58 AM
Last Post: newbieAuggie2019
  New Python learner looking for key word guidance naga 2 120 Nov-20-2019, 01:09 PM
Last Post: ChislaineWijdeven
  Sum char word dictionary RavCOder 3 150 Nov-08-2019, 01:32 PM
Last Post: perfringo

Forum Jump:


Users browsing this thread: 1 Guest(s)