-
-
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 agree with @serryachatterjee... the result is not a tuple!!! I actually ran it to be certain, and got "<class 'list'>".
This is my answer:
mylist = ["hi", 4, 8.99, "apple", ("t,b","n")]
result = [(tuple([index, mylist[index]])) for index in range(len(mylist))]
print(result)
@avanoc wdym? I printed the type and it said it was a tuple. I'm new to list comprehension so forgive me if I'm saying something wrong.
strr=["hi", 4, 8.99, 'apple', ('t,b','n')]
l=[(strr.index(x),x) for x in strr]
l
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)))
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)
but the result is not a tuple, it's a list right?