Skip to content

Instantly share code, notes, and snippets.

@bbookman
Created December 26, 2018 21:57
Show Gist options
  • Save bbookman/1bd5d6ef798e1c56cd00db70e8661759 to your computer and use it in GitHub Desktop.
Save bbookman/1bd5d6ef798e1c56cd00db70e8661759 to your computer and use it in GitHub Desktop.
Python List Comprehension: Get index and value from list
'''
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)
@RafaelMVDev
Copy link

@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.

@sanhiitaa
Copy link

strr=["hi", 4, 8.99, 'apple', ('t,b','n')]
l=[(strr.index(x),x) for x in strr]
l

@arutrr0
Copy link

arutrr0 commented Mar 16, 2023

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)))

@brian-yao
Copy link

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.

@OmikronWeapon
Copy link

@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"

@ranathungaWK
Copy link

ranathungaWK commented Mar 16, 2024

`items = ["hi", 4, 8.99, 'apple', ('t,b','n')]

new_list = [(items.index(j),j) for j in items]

print(new_list)`

@Christian-Stefan
Copy link

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment