1

I have a list containing a group of numbers (str) , and I want to check if there is at least one element in the list starting with '+' .

The problem with my code is that an infinite loop will occur if no number starts with '+', I need a better solution?

my_list = ['11112352', '222222003', '5682052003', '21543003', '98756003', '+004454883']
while True:
    for number in my_list:
        if number.startswith('+'):
            break
Red
  • 26,798
  • 7
  • 36
  • 58
Faith
  • 13
  • 3
  • 2
    Avoid using `while` loops for such problems and stick with just for loops if possible since all you are doing is iterating through each element of the list – Melvin Abraham Nov 17 '20 at 15:44
  • Hi!Welcome to SO! Could you please indicate why you need the `while` loop? Your problem requires iterating through each element of the list and break if a string starts with +. Hence the while loop is not necessary. – Ganesh Tata Nov 17 '20 at 15:45
  • Hey, thanks, My problem is to check that there is at least one element starting with '+' in the list , I am asking for a better solution – Faith Nov 17 '20 at 15:47
  • [Using `startswith` for a single character is inefficient](https://stackoverflow.com/q/13270888/13552470). As in my answer, simply use a slice of `[0]`. – Red Nov 17 '20 at 15:59
  • we can use startswith for one or multiple characters , it's a more generic solution that we can apply for different cases , that's why I accepted it – Faith Nov 17 '20 at 16:05

6 Answers6

2
my_list = ['11112352', '222222003', '5682052003', '21543003', '98756003', '+004454883']
for number in my_list:
    if number.startswith('+'):
        break

This:

while True:

is unnecessary, the for loop will already check every item in the list

To make it clearer, if it print every iteration:

my_list = ['11112352', '222222003', '5682052003', '21543003', '98756003', '+004454883']
for number in my_list:
    print(number)
    if number.startswith('+'):
        break

I get

11112352
222222003
5682052003
21543003
98756003
+004454883

so as you can see the while loop is unnecessary

coderoftheday
  • 1,987
  • 4
  • 7
  • 21
2

To check if any element starts with a '+', use builtin functions any and str.startswith. You can nearly write down the exact words as Python code:

starts_with_plus = any(element.startswith('+') for element in my_list)

This will return a boolean value. This will also return on the first instance where the condition is True, like returning out of a loop, making this very efficient.

If you want to check for other prefixes as well, just put it in a small function:

def starts_with(lst, prefix):
    return any(element.startswith(prefix) for element in lst)

starts_with_plus = starts_with(my_list, '+')
Jan Christoph Terasa
  • 5,781
  • 24
  • 34
1

Here's a simpler solution:

my_list = ['11112352', '222222003', '5682052003', '21543003', '98756003', '+004454883']
result = [x for x in my_list if x.startswith('+')]
if result:
    # do something if result is not empty
else:
    # result is empty -- no '+' entries in my_list
Tom Barron
  • 1,554
  • 18
  • 23
  • 1
    An issue with this is, for example, if the list is really really long, and say the first element starts with a `+`, you would still be checking every element in the list unnecessarily. – Sash Sinha Nov 17 '20 at 15:50
1

If you just need a True/False result, you can try this:

any(number for number in my_list if number[0] == "+")

Function any delivers True if at least one element of the list passed as argument is True.

Edited as suggested by Ann Zen. See also How exactly any works

  • 1
    This is inefficient as it will need to process *all* the strings before returning `True`/`False`. Please refer to my answer for the proper way of using `any`. – Red Nov 17 '20 at 15:55
  • 1
    The enclosing `[ ]` are actually counter-productive here since they'll force the whole list to be evaluated. – tzaman Nov 17 '20 at 15:55
0

Use the any method:

my_list = ['11112352', '222222003', '5682052003', '21543003', '98756003', '+004454883']
print(any(s[0] == '+' for s in my_list))

Output:

True
Red
  • 26,798
  • 7
  • 36
  • 58
0

You can do this with the help of a for loop and a flag variable:

flag = 0

for item in my_list:
    if item.startswith('+'):
        flag = 1
        break

print(flag)

If you get an output of 0, then it's obvious that no element starts with a +. On the other hand, if the output of the print statement is 1, there's at least one element that starts with a +.

Melvin Abraham
  • 2,870
  • 5
  • 19
  • 33