Understanding some charactor in python

Hi Below is code for separate some ip address. Anyone can help understand second line and 4th line why using []
Thank you

IPs = ['192.168.1.1', '192.168.2.1-10']
expanded_ip_list = []
for ip in IPs:
    if '-' in ip.split('.')[3]:
        prefix = '.'.join(ip.split('.')[:3])
        high_low = ip.split('.')[3].split('-')
        r = range(int(high_low[0]), int(high_low[1])+1, 1)
        for x in r:
            expanded_ip_list.append('{0}.{1}'.format(prefix,x))
    else:
        expanded_ip_list.append(ip)

print(expanded_ip_list)

By davidy2001 via Discussions on Python.org at 19Aug2022 16:58:

Hi Below is code for separate some ip address. Anyone can help
understand second line and 4th like why using []

Second line:

expanded_ip_list = []

This is just the Python syntax for an empty list, a list with no
members, of length 0. So this code starts with an empty list named
expanded_ip_list and appends things to it during the loop.

Fourth line:

if '-' in ip.split('.')[3]:

This is doing a few things in one go, and could do with a nice
explainatory comment. Let’s take this in pieces:

  • ip is each string from IPs in turn, courtesy of the for-loop
  • ip.split('.') is that string split into a list of strings based on
    dot spearators (the '.' parameter to split) eg ['192','168','2','1-10']
  • ip.split('.')[3] is the string from that list at index 3 i.e. the
    fourth string in the list eg '1-10'
  • '-' in ip.split('.')[3] tests whether there is a dash in that string

The intent here is to recognise a string like '192.168.2.1-10' as
indicating a range of addresses because of the 1-10 at the end.

The “true” branch of that if-statement then does some fiddly and hard to
read mucking about to get the prefix (192.168.2) and the numbers from
the suffix and to make the various .1, .2, .3 etc numbers that the
suffix is supposed to indicate.

Cheers,
Cameron Simpson cs@cskk.id.au