0

I want to find the difference between the last element and the second last element of the array where the array changes dynamically.

Please go through the code.

import requests
import json
from bs4 import BeautifulSoup as bs
import datetime, threading
LTP_arr=[]
url = 'https://nseindia.com/live_market/dynaContent/live_watch/get_quote/GetQuoteFO .jsp?underlying=RELIANCE&instrument=FUTSTK&expiry=30MAY2019&type=-&strike=-'

def ltw():
    resp = requests.get(url)
    soup = bs(resp.content, 'lxml')
    data = json.loads(soup.select_one('#responseDiv').text.strip())
    LTP=data['data'][0]['lastPrice']
    LTP_arr.append(LTP)
    print(LTP_arr)
    threading.Timer(1, tvwap).start()   

ltw()

At a particular time if the array is LTP_arr=['34','65','66','32','81'] Output should be given as 49. Then on next time frame if the LTP_arr=['34','65','66','32','81','100'] output sholuld be shown as 19

3
  • What is ltw()? Your code is very poorly formatted. However, use int(LTP_arr[-1])-int(LTP_arr[-2]). Surround the expression with abs() if you want the absolute value. Commented May 23, 2019 at 19:08
  • Indenting is important in python. Please reformat your code. I don't know when you function ends. Commented May 23, 2019 at 19:09
  • Thank you. Will take care of the format henceforth Commented May 23, 2019 at 22:03

1 Answer 1

2

You can access last element with [-1] LTP_arr[-1] give you '81', which is a string. Cast with int() You can do the same thing with [-2]

int(LTP_arr[-1]) - int(LTP_arr[-2])

You can add a try / except if your value can be cast by int()

try:
    int(LTP_arr[-1]) - int(LTP_arr[-2])
except IndexError:
    # do what you want to handle this error
Sign up to request clarification or add additional context in comments.

2 Comments

You will want a try/except for IndexError as well.
I edit my post :) But sometimes you are sure about the data type. So try/except can be avoid if you know the data source

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.