-2

I'm a novice coding learner. I am trying to extract numbers only in sequential from the list.

for example, my list is:

s = [2, 4, 6, 7, 8, 9, 10, 13, 14, 15]

from this list I want only the numbers in sequential:

6,7,8,9,10, 13,14,15

so, I have the following code, but it doesn't work.

s = [2, 4, 6, 7, 8, 9, 10, 13, 14, 15]


for i in s:
    if s[i+1] - s[i] == 1:
        print(s[i])

could you give me some idea? Thank you.

vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20

3 Answers3

0

you are looping over the items of the list instead of the indices of these items. To loop over the indices use:

if s[1] - s[0] == 1:
    print(s[0])
for i in range(1,len(s)):
    if s[i] - s[i-1] == 1: 
        print(s[i])
onno
  • 969
  • 5
  • 9
0

I just solved this question. thank you all for commenting.

s = [2, 4, 6, 7, 8, 9, 10, 13, 14, 15]
a = []
for i in range(len(s)-1):
    if s[i] - s[i+1] == -1:
        a. append(s[i])
        a. append(s[i+1])

print(set(a))
0

I would iterate through the list s storing the results in set res and at the end, if I want the results sorted, I would apply the sorted function on res to get the output.

Here is some code.

s= [2, 4, 6, 7, 8, 9, 10, 13, 14, 15]
res = set()
for i, num in enumerate(s[:-1]):
    if num+1 == s[i+1]:
        res = res.union({num} )           
        res = res.union({s[i+1]})
print(sorted(res))
print(res)

And the output is:

>>> [6, 7, 8, 9, 10, 13, 14, 15]
    {6, 7, 8, 9, 10, 13, 14, 15}

Keep in mind that sets are NOT sorted even if they appear to be sorted. This is because sets DO NOT support indexes. So if you want your results sorted, make sure to apply the sorted function to be on the safe side.

Samuel Nde
  • 2,565
  • 2
  • 23
  • 23