-1

Example:

list = ["A", "B", "C", "D"]
for item in list: 
    print(item + "01")

If I do this, I rename all items in the list. But what if I want to ignore B or C or both of them?

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
Strider90
  • 7
  • 1

4 Answers4

0

Compare item before printing, if item is not equal to "B" or "C", rename it

for item in list:
 if item != "B" or item !="C":
  print(item + "01")

Or pass exclusion strings list to your definition and check if item present in that list

def rename(list, excludeList):
 for item in list:
  if item not in excludeList:
    print(item + "01")

rename(["A","B","C","D"], ["B","C"])
smnth90
  • 750
  • 5
  • 14
0

I modified part of your code, so my answer is not too different from your question. If you want a new list with some of your items changed, here's the code:

list = ["A", "B", "C", "D"]
newlist = []

for item in list:
    if (item != "B") and (item != "C"):
        newlist.append(item + "01")
    else:
        newlist.append(item)

print(newlist)

The output is:["A01", "B", "C", "D01"]

Else, if you want to print your elements one by one, here's the code:

list = ["A", "B", "C", "D"]

for item in list:
    if (item != "B") and (item != "C"):
        print(item + "01")
    else:
        print(item)

The output is:

A01
B
C
D01
hellomynameisA
  • 546
  • 1
  • 7
  • 28
0

This is just to add to what the other answers already have. In case your list is actually much longer, you may want to test whether the item is part of another list of items, here called exclude_list that has the names of the values you do not want to append 01 to.

I assume here that you still want to print B and C, as is, in the final output, rather than completely exclude them.

list_letters = ["A", "B", "C", "D"]
exclude_list = ["B", "C"] 

for item in list_letters:
    if not item in exclude_list:
        print(item + "01")
    else:
        print(item)

This will output:

A01
B
C
D01
linamnt
  • 1,315
  • 1
  • 12
  • 23
-1

If you prepare a set of items which you want to ignore (I named it excluded), you may use it for excluding them from renaming:

lst = ["A", "B", "C", "D"]
excluded = {"B", "C"}

for item in lst: 
    if item not in excluded:
        print(item + "01")
MarianD
  • 13,096
  • 12
  • 42
  • 54