Home > front end >  I'm completely new to python, and was just practicing lists, and I tried running a for loop
I'm completely new to python, and was just practicing lists, and I tried running a for loop

Time:01-31

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []

for x in fruits:
  if "a" in x:
    newlist.append(x)

print(newlist)

ABOVE CODE WORKS

So I tried running a for loop. What I'm trying to do is, I have 2 lists, and if there is something in my list that contains "a", and if it contains "a", it will be added to the second list

So I did this, just to practice my skills on lists and found that it does not work:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []

for x in fruits:
  if "a" in x:
    newlist.extend(fruits)

print(newlist)

OUTPUT:

['apple', 'banana', 'cherry', 'kiwi', 'mango', 'apple', 'banana', 'cherry', 'kiwi', 'mango', 'apple', 'banana', 'cherry', 'kiwi', 'mango']


** Process exited - Return Code: 0 **
Press Enter to exit terminal

And I want someone to explain to me step by step what is happening, why I am wrong, and what other methods I can use to get the output I want

WANTED OUTPUT FOR NEWLIST:

['apple', 'banana', 'mango']


** Process exited - Return Code: 0 **
Press Enter to exit terminal

CodePudding user response:

You can try using newlist.append() instead of extend(). I believe the extend() method adds all of the elements inside an iterable, in this case the original list.

Btw. you are using fruits as a parameter for extend(). This is wrong by itself and defeates the purpose of iterating thorough your list elements. You should instead use the variable 'x' in this case if you want to go thorough your list.

CodePudding user response:

In the first iteration of the loop: x="apple" and the condition if "a" in x is True

What newlist.extend(fruits) does is adds all the contents of fruits which is ["apple", "banana", "cherry", "kiwi", "mango"] into the newlist.

On the 2nd and 5th iteration (i.e 'banana' and 'mango') the contents of the fruits list (all the fruits) is again added to the newlist.

As a result, when you print(newlist), it prints all the fruits repeated 3 times.

CodePudding user response:

you are using extend function which adds all elements. So basically , if any String in fruits contains a all Strings will be added.

CodePudding user response:

Basically:

  • .append() will add every word containing the letter "a" to the newlist.
  • .extend() will add the whole list every time it finds a word with the letter "a".

3 words with the letter "a" in the original list, so the whole list was added 3 times as well to newlist.

Keep practicing in due time you will be able to avoid using .append() as well in certain situations like:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
  • Related