Aditya Taide
Aditya Taide

Reputation: 57

How to add two different elements from the same array which changes dynamically?

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

Upvotes: 0

Views: 34

Answers (1)

Wilfried
Wilfried

Reputation: 1633

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

Upvotes: 2

Related Questions