Python :function that takes an iterable argument and generates tuples

python iterable type
python function type
python function tuple argument
python tuple functions and methods
python zip function example

I try to do something on python.

I try to write a function that takes an iterable argument and generates tuples of 2 elements:

  1. the current iterable element
  2. the number of times it has been generated since the beginning

Here is my code

liste = ['a','b','a','a','b']

compte = {}.fromkeys(set(liste),0)
for valeur in liste:
     compte[valeur] += 1


output :

{'b': 2, 'a': 3}

But I want to obtain "a:1" "b:1" "a:2" "a:3" and "b:2"

Thanks for help

Your expected result is a list, not a dictionary. A fix to your code would be to use your dict for counting, but appending to a list:

>>> liste = ['a','b','a','a','b']
>>> compte = dict.fromkeys(liste,0) #Or use a default dict
>>> result = []
>>> for valeur in liste:
...  compte[valeur] += 1
...  result.append((valeur,compte[valeur]))
>>> print(result)
[('a', 1), ('b', 1), ('a', 2), ('a', 3), ('b', 2)]

Python :function that takes an iterable argument and generates tuples, I try to do something on python. I try to write a function that takes an iterable argument and generates tuples of 2 elements: the current iterable  The tuple() function is a built-in function in Python that can be used to create a tuple. A tuple is an immutable sequence type. Syntax:

You can just modify your code in this way:

liste = ['a','b','a','a','b']

liste2 = []
compte = {}.fromkeys(set(liste),0)
for valeur in liste:
    compte[valeur] += 1
    liste2.append(valeur + ':' + str(compte[valeur]))


It is important to say: what you are trying to do it is not a tuple, but a list, because it is mutable. Your compte variable is a dictionary.

Python, tuple(iterable). Parameters: This function accepts a single parameter iterable (​optional). Returns: It does not returns any-thing but creates a tuple. Error and  Python’s zip() function is defined as zip(*iterables). The function takes in iterables as arguments and returns an iterator. This iterator generates a series of tuples containing elements from each iterable. zip() can accept any type of iterable, such as files, lists, tuples, dictionaries, sets, and so on.

Use a generator function.

from collections import defaultdict

def with_running_count(values):
    counts = defaultdict(int)
    for value in values:
        counts[value] += 1
        yield value, counts[value]

>>> print(*with_running_count('abaab'))

('a', 1) ('b', 1) ('a', 2) ('a', 3) ('b', 2)

One advantage of using a generator over the other suggestions is that generators are lazy. That means that you can pass in iterators that return an endless (or very large) data stream, since the generator only consumes the input stream when needed.

# an endless iterator
coin = iter(lambda: random.choice(['heads', 'tails']), None)

# the running count will also be endless        
toss = with_running_count(coin)

>>> next(toss), next(toss), next(toss)
(('tails', 1), ('tails', 2), ('heads', 1))

9.7. itertools, The same effect can be achieved in Python by combining imap() and count() to form imap(f, combinations(), p, r, r-length tuples, in sorted order, no repeated elements Gets chained inputs from a single iterable argument that is evaluated lazily. It generates a break or new group every time the value of the key function  One of the built-in function in Python interpreter is python any(). Python any() takes iterable as an argument and returns True if any of the element in the iterable is true. If iterable is empty, then the Python any() Function returns False.

You can initialize the dictionary with counts as you go:

liste = ['a','b','a','a','b']
compte = {}
result = []
for valeur in liste:
    compte[valeur] = compte.get(valeur, 0) + 1
    result.append((valeur, compte[valeur]))


2. Built-in Functions, This generates a string similar to that returned by repr() in Python 2. For other containers see the built-in list, set, and tuple classes, as well as the collections module. If additional iterable arguments are passed, function must take that many  If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see itertools.starmap().

You can use Counter from collections module:

from collections import Counter

liste = ['a','b','a','a','b']

def counter(iterable):
    c = Counter()
    for i in iterable:
        yield i, c[i]



[('a', 1), ('b', 1), ('a', 2), ('a', 3), ('b', 2)]

typing — Support for type hints, The function below takes and returns a string and is annotated as follows: In the function greeting , the argument name is expected to be of type str and the return from typing import TypeVar, Iterable, Tuple, Union S = TypeVar('S') Response TypedDict creates a dictionary type that expects all of its instances to have a  Lists and tuples are arguably Python’s most versatile, useful data types.You will find them in virtually every nontrivial Python program. Here’s what you’ll learn in this tutorial: You’ll cover the important characteristics of lists and tuples.

itertools — Functions creating iterators for efficient looping, Gets chained inputs from a single iterable argument that is evaluated lazily. So, if the input iterable is sorted, the combination tuples will be produced in sorted order It generates a break or new group every time the value of the key function​  So by passing no argument, zip returns an empty iterator. However, if we pass two iterable object of same lengths, then an iterable of python tuples will be returned where each element of the tuple will be from those iterable lists. Python zip function is mainly used to combining data of two iterable elements together. See the following code.

Python Fundamentals Tutorial: Advanced Types: Containers, The list() function also takes an iterable as a single argument and returns a shallow with the list() function, a new list of the characters can easily be generated. > Similar to lists, empty tuples can be created with an empty pair of parentheses,  Usage: T = TypeVar ('T') # Can be anything A = TypeVar ('A', str, bytes) # Must be str or bytes Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function definitions. See class Generic for more information on generic types.

Iterables, Familiar examples of iterables include lists, tuples, and strings - any such sequence It is also possible to have an iterable that “generates” each one of its members Here are some useful built-in functions that accept iterables as arguments:. The syntax of the zip() function is given below. It takes a variable number of parameters that are basically different tables that contain similar data that can be mapped together in the resultant iterable. So, this function returns an iterable that contains the data from provided iterable arguments mapped together.

  • You cannot have a dictionary with identical keys. Maybe a list is what you are looking for? Seems like order is important in the result.
  • Also note that calling fromkeys on an instance of dict creates that instance pointlessly; it's a class method.