Answers for "iterate through tuple python"

27

python3 iterate through indexes

items=['baseball','basketball','football']
for index, item in enumerate(items):
    print(index, item)
Posted by: Guest on May-07-2020
37

python iterate through dictionary

a_dict = {'apple':'red', 'grass':'green', 'sky':'blue'}
for key in a_dict:
  print key # for the keys
  print a_dict[key] # for the values
Posted by: Guest on November-12-2019
0

named tuple python iterate

>>> a = A(1, 2)
>>> for name, value in a._asdict().iteritems():
    print name
    print value


a
1
b
2

>>> for fld in a._fields:
    print fld
    print getattr(a, fld)


a
1
b
2
Posted by: Guest on September-16-2021
-1

python tuple iterate

You could google on "tuple unpacking". This can be used in various places in Python. The simplest is in assignment

>>> x = (1,2)
>>> a, b = x
>>> a
1
>>> b
2
In a for loop it works similarly. If each element of the iterable is a tuple, then you can specify two variables and each element in the loop will be unpacked to the two.

>>> x = [(1,2), (3,4), (5,6)]
>>> for item in x:
...     print "A tuple", item
A tuple (1, 2)
A tuple (3, 4)
A tuple (5, 6)
>>> for a, b in x:
...     print "First", a, "then", b
First 1 then 2
First 3 then 4
First 5 then 6
The enumerate function creates an iterable of tuples, so it can be used this way.
Posted by: Guest on March-20-2021

Code answers related to "iterate through tuple python"

Python Answers by Framework

Browse Popular Code Answers by Language