-
-
Save bbookman/1bd5d6ef798e1c56cd00db70e8661759 to your computer and use it in GitHub Desktop.
''' | |
Get the index and the value as a tuple for items in the list ["hi", 4, 8.99, 'apple', ('t,b','n')]. Result would look like [(index, value), (index, value)] | |
''' | |
items = ["hi", 4, 8.99, 'apple', ('t,b','n')] | |
result = [(index, item) for index, item in enumerate(items)] | |
print(result) |
I understand this is just an exercise but simply print(list(enumerate(items)))
produces the same output in a more concise manner. The solution here is extra code for no reason.
@arutrr0 list comprehensions make lists already, so there's no need to use the list() function. as long as you use square brackets.
print([(i, items[i]) for i in range(len(items))])
@avanoc I took the exercise to mean it should be a list of tuples. It does say the result should be a tuple, which makes it ambiguous, but since the exercise is about list comprehensions, it makes sense the result has to be a list (of tuples), and the poster simply forget to specific "list of tuples"
`items = ["hi", 4, 8.99, 'apple', ('t,b','n')]
new_list = [(items.index(j),j) for j in items]
print(new_list)`
test_string = ['hi',4, 9,8.99,'apple',('t','b','n')]
Printed as a dictionary
Dictionary = {i:test_string[i] for i in range(len(test_string))}
print(Dictionary)
List = [x for x in enumerate(test_string)]
print(List)
items = ["hi", 4, 8.99, 'apple', ('t,b','n')]
#first version:
print(list((i, items[i]) for i in range(len(items))))
#alternative version:
print(list((index, item) for index, item in enumerate(items)))