printing out tuples from function - python

Im making this function that prints the index number with the item from the string but I need it to print out as tuples, for example
[(0, 'dog'), (1, 'pig'), (2, 'cow')]
how would I go about doing this? it just prints each out on one line so far.
this is my code so far.
def my_enumerate(items):
"""return a list of tuples where item is the i'th item """
for item in items:
index = items.index(item)
print(item, index)
my_enumerate(['dog', 'pig', 'cow'])
thank you

def my_enumerate(items):
"""return a list of tuples where item is the i'th item """
l = []
for index in range(len(items)):
t = (index, items[index])
l.append(t)
return l
res = my_enumerate(['x', 'x', 'x'])
print(res)

I would suggest:
def my_enumerate(items):
print([(i, animal) for i, animal in enumerate(items)])

the reason you are printing them one by one is that you are printing them one by one inside the loop, to get all of them at once you will need to create a list and print that at the end of the loop. there are several ways to go about this and m0nte-cr1st0 gave you the most legible one, ill give you something a little shorter:
def my_enumerate(items):
return list(zip(range(len(items)), items))
zip lets you smoosh together 2 lists pairwise
this solution of course assumes you cant just use the built in enumerate

In expression
print(list(enumerate(items)))
part enumerate(['dog', 'pig', 'cow']) will create an iterator over the list of tuples [(0, 'dog'), (1, 'pig'), (2, 'cow')] you want to print , so you can just create a list with this iterator and print it.

Related

What does this Python 3 function do?

Can anybody help me to find out how this function works?
def get_matched_birthdays(birthdays):
if len(birthdays) == len(set(birthdays)):
return None
for a, birthdayA in enumerate(birthdays):
for b, birthdayB in enumerate(birthdays[a+1:]):
if birthdayA == birthdayB:
return birthdayA
Here is birthdays: https://ghostbin.com/paste/4tM0V
I am understanding the first two lines but what's happening inside those two for loops?
The function basically loops through the "birthdays" list and checks to see if an element appears further down the list and returns the value every time it sees it down the line.
First for loop just loops through the "birthdays" list and gives each element an index which is stored in variable "a".
for a, birthdayA in enumerate(birthdays):
The second loop takes a subset of "birthdays" list and loops through it. The subset starts at the index "a+1" and ends at the end of the "birthdays" list.
for b, birthdayB in enumerate(birthdays[a+1:]):
The function then returns the values where the items in "birthdays" list comes up again in the list.
if birthdayA == birthdayB:
return birthdayA
If you want a more efficient way of checking for dupes and returning the index of dupes perhaps use something like this:
>>> dupes_lst = []
>>> unique_set = set()
>>> lst = [1,2,3,1,1,4,2]
>>> for i, item in enumerate(lst):
... if item in unique_set:
... dupes_lst.append(i)
... else:
... unique_set.add(item)
More on enumerate at https://docs.python.org/3/library/functions.html :
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

How does this python enumerate script work and what makes it so fast? [duplicate]

What does for row_number, row in enumerate(cursor): do in Python?
What does enumerate mean in this context?
The enumerate() function adds a counter to an iterable.
So for each element in cursor, a tuple is produced with (counter, element); the for loop binds that to row_number and row, respectively.
Demo:
>>> elements = ('foo', 'bar', 'baz')
>>> for elem in elements:
... print elem
...
foo
bar
baz
>>> for count, elem in enumerate(elements):
... print count, elem
...
0 foo
1 bar
2 baz
By default, enumerate() starts counting at 0 but if you give it a second integer argument, it'll start from that number instead:
>>> for count, elem in enumerate(elements, 42):
... print count, elem
...
42 foo
43 bar
44 baz
If you were to re-implement enumerate() in Python, here are two ways of achieving that; one using itertools.count() to do the counting, the other manually counting in a generator function:
from itertools import count
def enumerate(it, start=0):
# return an iterator that adds a counter to each element of it
return zip(count(start), it)
and
def enumerate(it, start=0):
count = start
for elem in it:
yield (count, elem)
count += 1
The actual implementation in C is closer to the latter, with optimisations to reuse a single tuple object for the common for i, ... unpacking case and using a standard C integer value for the counter until the counter becomes too large to avoid using a Python integer object (which is unbounded).
It's a builtin function that returns an object that can be iterated over. See the documentation.
In short, it loops over the elements of an iterable (like a list), as well as an index number, combined in a tuple:
for item in enumerate(["a", "b", "c"]):
print item
prints
(0, "a")
(1, "b")
(2, "c")
It's helpful if you want to loop over a sequence (or other iterable thing), and also want to have an index counter available. If you want the counter to start from some other value (usually 1), you can give that as second argument to enumerate.
I am reading a book (Effective Python) by Brett Slatkin and he shows another way to iterate over a list and also know the index of the current item in the list but he suggests that it is better not to use it and to use enumerate instead.
I know you asked what enumerate means, but when I understood the following, I also understood how enumerate makes iterating over a list while knowing the index of the current item easier (and more readable).
list_of_letters = ['a', 'b', 'c']
for i in range(len(list_of_letters)):
letter = list_of_letters[i]
print (i, letter)
The output is:
0 a
1 b
2 c
I also used to do something, even sillier before I read about the enumerate function.
i = 0
for n in list_of_letters:
print (i, n)
i += 1
It produces the same output.
But with enumerate I just have to write:
list_of_letters = ['a', 'b', 'c']
for i, letter in enumerate(list_of_letters):
print (i, letter)
As other users have mentioned, enumerate is a generator that adds an incremental index next to each item of an iterable.
So if you have a list say l = ["test_1", "test_2", "test_3"], the list(enumerate(l)) will give you something like this: [(0, 'test_1'), (1, 'test_2'), (2, 'test_3')].
Now, when this is useful? A possible use case is when you want to iterate over items, and you want to skip a specific item that you only know its index in the list but not its value (because its value is not known at the time).
for index, value in enumerate(joint_values):
if index == 3:
continue
# Do something with the other `value`
So your code reads better because you could also do a regular for loop with range but then to access the items you need to index them (i.e., joint_values[i]).
Although another user mentioned an implementation of enumerate using zip, I think a more pure (but slightly more complex) way without using itertools is the following:
def enumerate(l, start=0):
return zip(range(start, len(l) + start), l)
Example:
l = ["test_1", "test_2", "test_3"]
enumerate(l)
enumerate(l, 10)
Output:
[(0, 'test_1'), (1, 'test_2'), (2, 'test_3')]
[(10, 'test_1'), (11, 'test_2'), (12, 'test_3')]
As mentioned in the comments, this approach with range will not work with arbitrary iterables as the original enumerate function does.
The enumerate function works as follows:
doc = """I like movie. But I don't like the cast. The story is very nice"""
doc1 = doc.split('.')
for i in enumerate(doc1):
print(i)
The output is
(0, 'I like movie')
(1, " But I don't like the cast")
(2, ' The story is very nice')
I am assuming that you know how to iterate over elements in some list:
for el in my_list:
# do something
Now sometimes not only you need to iterate over the elements, but also you need the index for each iteration. One way to do it is:
i = 0
for el in my_list:
# do somethings, and use value of "i" somehow
i += 1
However, a nicer way is to user the function "enumerate". What enumerate does is that it receives a list, and it returns a list-like object (an iterable that you can iterate over) but each element of this new list itself contains 2 elements: the index and the value from that original input list:
So if you have
arr = ['a', 'b', 'c']
Then the command
enumerate(arr)
returns something like:
[(0,'a'), (1,'b'), (2,'c')]
Now If you iterate over a list (or an iterable) where each element itself has 2 sub-elements, you can capture both of those sub-elements in the for loop like below:
for index, value in enumerate(arr):
print(index,value)
which would print out the sub-elements of the output of enumerate.
And in general you can basically "unpack" multiple items from list into multiple variables like below:
idx,value = (2,'c')
print(idx)
print(value)
which would print
2
c
This is the kind of assignment happening in each iteration of that loop with enumerate(arr) as iterable.
the enumerate function calculates an elements index and the elements value at the same time. i believe the following code will help explain what is going on.
for i,item in enumerate(initial_config):
print(f'index{i} value{item}')

Flatten a list of lists of tuples

I have read several posts on the question "how to flatten lists of lists of lists ....". And I came up with this solution:
points = [[[(6,3)],[]],[[],[]]]
from itertools import chain
list(chain.from_iterable(points))
However my list looks sometimes like this:
[[[(6,3)],[]],[[],[]]]
Not sure if it is correct but I hope you understand.
The point is the leaf element is a tuple and when calling the above code it also removes the tuple and just returns [6,3].
So what could i do to just get [(6,3)] ?
How about this,
lists = [[[(6,3)],[]],[[],[]]]
r = [t for sublist in lists for l in sublist for t in l]
print(r)
# [(6, 3)]
maybe its not the best solution, but it works fine:
def flat(array):
result = []
for i in range(len(array)):
if type(array[i]) == list:
for j in flat(array[i]):
result.append(j)
else:
result.append(array[i])
return result
print flat([[[(6,3)],[]],[[],[]]] )
and the result is:
>>>
[(6, 3)]
>>>

Index a tuple by calling one of its elements

I'm trying to write a function that takes in
a list of tuples with partygoers names and their priority and
the max number of people that can get it. I'm currently trying to put tuples in ascending order based on one of its elements.
I have a list or tuples:
alist =[('Carlos', 1), ('Gretchen', 8), ('Abby', 6),('Sam', 4)]
so far Ive made a list of all of the numbers in order with this code:
def party_time(alist,maxnum):
newlist = []
finallist=[]
while len(finallist) < maxnum:
for tup in alist:
rank = tup[1]
newlist.append(rank)
newlist.sort()
newlist = [1,4,6,8]
Is there a way to use a for loop to go through newlist and index the tuple by using the number in newlist? Or will it just index where the number is in the tuple?
This should do it:
def party_time(alist, maxnum):
sorted_list = sorted(alist, key=lambda p: p[1], reverse=True)
return sorted_list[:maxnum]

How to add lower function to this code

I want to print my output in lowercase, but I am not getting the correct results. Here's my code. Please help!
import csv
mags = csv.reader(open("mags.csv","rU"))
for row in mags:
print [row[index] for index in (1, 0)]
print [item.lower( ) for item in row]
List comprehension can be nested, like so
print [item.lower() for item in [row[index] for index in (1, 0)]]
Don't have an interpreter handy to test this, tho.
You can nest the two comprehensions like this:
print [item.lower() for item in [row[index] for index in (1, 0)]]
That way you'll use the data from the first comprehension (the second and first item of the row in this order) as input for the second one (lowercase everything).
You can also slice the row instead of using a comprehension for the first one:
print [item.lower() for item in row[::-1][-2:]] # Slicing in 2 steps: [::-1] reverses the list and [-2:] returns the last two items of the reversed list
or (Shorter, but reversed indices slicing doesn't work as you'd think)
print [item.lower() for item in row[1::-1] # Same thing, but it helps to break these things up into steps
Are you sure that the row is a list of strings here ?
I see correct output :
>>> row = [ "alpA", "bETA","gammA" ]
>>> print [item.lower( ) for item in row]
['alpa', 'beta', 'gamma']
>>>

Categories

Resources