Creating a tuple using a for loop.

I'm new to Python, and although I did some updating in Codecademy, I'm having difficulty with this first task.

"Task 1. Open the code skeleton file" i772_assg1.py "and execute the list_ele_idx (li) function. You must write a" loop "that reads the elements of the list, and for each element you create a tuple (element, index) to write the element and its index (position) in the list. This function takes as an argument the list “li.” The return value of the function should be a list (element, index). In the main method, I wrote a test case for task 1. Please do not comment on the test case and check its function.

This is what I am trying, but I am not getting anything. Any feedback would be greatly appreciated, as this is my first stack overflow post!

def list_ele_idx(li):
    index = 0 # index
    element = [(5,3,2,6)]
    li = [] # initialze a list; you need to add a tuple that includes an element and its index to this list
    # your code here. You must use for loop to read items in li and add (item,index)tuples to the list lis
    for index in li:
        li.append((element, index))
    return li # return a list of tuples
+4
source share
2 answers

Go through your code step by step so that you understand the mistakes you make, and then take a look at the right solution. Finally, let's look at a pythonic solution that can annoy your teacher.

Line

index = 0

excellent because you want to start counting indices to zero. Line

element = [(5,3,2,6)]

doesn't make sense because your function should work for any given list, not just your test case. So let me remove it. You initialize your list of results with

li = []

, li, , .

result = []

. li

for index in li:

li , . index , , .

li.append((element, index))

for , index, element - , .

:

def list_ele_idx(li):
    index = 0 # start counting at index 0
    result = [] # initialize an empty result list
    for item in li: # loop over the items of the input list
        result.append((item, index)) # append a tuple of the current item and the current index to the result
        index += 1 # increment the index
    return result # return the result list when the loop is finished

enumerate(li) , , . , :

def list_ele_idx(li):
    return [(y,x) for x,y in enumerate(li)]
+6

Python, :

def list_ele_idx(li):
    tuple_list = []
    for index, item in enumerate(li):
        tuple_list.append((index, item))
    return tuple_list
+1

Source: https://habr.com/ru/post/1626696/


All Articles