Suppose I have an iterable:
var = "ABCDEF"
I get the iterable like this:
it = itertools.combinations(var,2)
Is there any single function to print all values of iterables like
printall(it)
rather than using the for
loop?
To print our iterable with a custom delimiter, we'll combine the splat operator and pass a custom delimiter. If we want to print each character line by line, use a newline character as the custom separator. This technique is not limited to strings. Use the same combination if you want to print a list, tuple, or set.
To loop through a set of code a specified number of times, we can use the range() function, The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
To create an object/class as an iterator you have to implement the methods __iter__() and __next__() to your object. As you have learned in the Python Classes/Objects chapter, all classes have a function called __init__() , which allows you to do some initializing when the object is being created.
Iterable is an object which can be looped over or iterated over with the help of a for loop. Objects like lists, tuples, sets, dictionaries, strings, etc. are called iterables. In short and simpler terms, iterable is anything that you can loop over.
This rather depends what you want, if you want to print out all the values, you need to compute them - an iterable doesn't guarantee the values are computed until after they are all requested, so the easiest way to achieve this is to make a list:
print(list(iterable))
This will print out the items in the normal list format, which may be suitable. If you want each item on a new line, the best option is, as you mentioned, a simple for loop:
for item in iterable: print(item)
If you don't need the data in a specific format, but just need it to be readable (not all on one line, for example), you may want to check out the pprint
module.
A final option, which I don't really feel is optimal, but mention for completeness, is possible in 3.x, where the print()
function is very flexible:
print(*iterable, sep="\n")
Here we unpack the iterable as the arguments to print()
and then make the separator a newline (as opposed to the usual space).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With