Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any single function to print an iterable's values?

Tags:

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?

like image 420
user192082107 Avatar asked Feb 22 '13 01:02

user192082107


People also ask

How do you print iterable in Python?

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.

How do you iterate a number in Python?

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.

How do you make a variable iterable in Python?

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.

What are the Iterables in Python?

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.


1 Answers

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).

like image 147
Gareth Latty Avatar answered Sep 26 '22 02:09

Gareth Latty