-11

I'm trying to get the result of every iterations of a for loop into a list, but when I run my code, I only get the last iteration's result in my list.

import ipaddress

user_input = input("")

network = ipaddress.IPv4Network(user_input)

for i in network.hosts():
    ipaddresses = i
print(ipaddresses)

The result is -

10.192.32.0/24
10.192.32.254
Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
vignesh
  • 5
  • 3

2 Answers2

0

If you want to get the results of every iterations of a for loop into a list, you need a list to store the values at each iteration.

import ipaddress
user_input = input("")
network = ipaddress.IPv4Network(user_input)

ipaddresses = [] #initiate an empty list

for i in network.hosts():
    ipaddresses.append(i)
print(ipaddresses)
Rahul
  • 10,830
  • 4
  • 53
  • 88
0

You always set ipadresses to the current value of i and therefor ipadress is always a string of the last i it was set equal to. A faster way to achieve your goal is to do a list comprehension:

    import ipaddress

    user_input = input("")
    network = ipaddress.IPv4Network(user_input)

    ipaddresses = [i for i in network.hosts()]

    print(ipaddresses)
  • A faster way to achieve your goal is to do a list comprehension? it is pythonic but not faster. – Rahul Jul 01 '17 at 10:47
  • List comprehensions are faster than doing the same in a for loop if I'm not completely mistaken – Marvin Taschenberger Jul 01 '17 at 10:48
  • You are completely mistaken. – Rahul Jul 01 '17 at 10:49
  • I'm sorry but they are, even for a simple sum of 100 elements, a list comprehension is more than twice as fast loop over the elements. Just try it out. – Marvin Taschenberger Jul 01 '17 at 10:55
  • https://stackoverflow.com/questions/22108488/are-list-comprehensions-and-functional-functions-faster-than-for-loops – Rahul Jul 01 '17 at 10:59
  • Yes and if i may cite it **A list comprehension is usually a tiny bit faster than the precisely equivalent for loop (that actually builds a list)**. So first i didn't claim that it is way faster for every use and i also tried it before with the timeit method for my claim. So you are wrong here, not me. – Marvin Taschenberger Jul 01 '17 at 11:04
  • Read all answers. It is sometimes slower. – Rahul Jul 01 '17 at 11:09
  • Anyway, the point of a list comprehension is not speed, but readability and writing comfort. It reduces the boilerplate of building simple lists, but trying hard to build a complex list through a comprehension might lead to awful things with multiple `for`s. – Right leg Jul 01 '17 at 11:10