Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude an element in a list [duplicate]

Is it possible to use slice but on a specific element on a list? For example a = [1,2,3,4,5,6,7,8,9] I want to make a for loop that prints out the whole list except the second element.

I want to make something like this:

for i in a[something_slice]: 
    print(i)

Is this possible?

like image 512
Amx Avatar asked Mar 01 '26 06:03

Amx


1 Answers

For excluding just one element, the 2 slice lst[:i] + lst[i + 1:] approach proposed by @Applet123 is probably the fastest (Or perhaps a excluded = lst.pop(1) to extract the excluded element and for x in lst: print(x) for printing all the others; then lst.insert(1,excluded) to put the excluded element back on the list. See data structures docs for details).

If you just want to filter out certain indexes, instead of a for loop I recommend you use a more pythonic (and intuitive) approach based on list comprehensions and enumerate:

myList = [1,2,3,4,5,6,7,8,9]
excludedIndices = [1]
myFilteredList = [x for i, x in enumerate(myList) if i not in excludedIndices]
print (myFilteredList)

# output:
# [1,3,4,5,6,7,8,9]

# or, to actually print each element individually:
for x in myFilteredList:
  print (x)

# which can also work as a 2-liner with inline filtering:
for i, x in enumerate(myList):
  if i not in excludedIndices: print(x)

Also check out python usage of filter and map builtin functions, which may be overkill for this purpose but still offer a general and more powerful solution for this kind of processing:

# filters an enumerated element 
def myFilter(element): 
  return element[0] not in excludedIndices

# maps an enumerated element to a function 
def myMap(element): 
  print(element[1])
  
# runs myMap function for each enumerated element on the list filtered by myFilter
for x in map(myMap,filter(myFilter,enumerate(myList))): pass

Which you can also turn into a one-liner using lambda expressions:

for x in map(lambda x: print(x[1]),filter(lambda x: x[0] not in excludedIndices,enumerate(myList))): pass
like image 113
NotGaeL Avatar answered Mar 03 '26 05:03

NotGaeL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!