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