Python lists, help needed
Hello! I'm new to programming and Python. I gave myself a challenge about manipulating lists and now I'm stuck. Here's my problem: I have two lists of strings. names =["Bulbasaur", "Ivysaur", "Venusaur", "Charmander", "Charmeleon", "Charizard", "Squirtle", "Wartortle", "Blastoise"] numbers = ["#1 ", "#2 ", "#3 ", "#4 ", "#5 ", "#6 ", "#7 ", "#8 ", "#9 "] I'd like to combine the two lists into a new list called pokedex, which should look like this: pokedex = ["#1 Bulbasaur", "#2 Ivysaur", "#3 Venusaur", and so on... ] Using a for loop I get ["#1 Bulbasaur", #1 Ivysaur", "#1 Venusaur", .... , "#2 Bulbasaur", "#2 Ivysaur", and so on...] How do I do it so I only add the first index of the first list to the first index of the second list, then the second to the second and so on?
1/18/2021 6:30:03 PM
Peter
10 Answers
New Answerwhat about names = ["Bulbasaur", "Ivysaur", "Venusaur", "Charmander", "Charmeleon", "Charizard", "Squirtle", "Wartortle", "Blastoise"] pokedex = [f'#{i} {j}' for i,j in enumerate(names,1)] print(*pokedex, sep='\n')
for i in range(len(names)): word = numbers[i] + " " + names[i] pokedex.append(word) Abhay solution is perfect for runaways, maybe a bit hard for you. Although you should study that brilliant snippet.
How about this one, based on Abhay 's solution. Maybe it is easier to understand with named variables. Things to look up: list comprehensions, zip, tuple pokedex = [f'{number} {name}' for number, name in zip(numbers,names)]
Looks like you used nested loops, which gave you every possible combination, but just a single loop is needed here
Thank you very much for your help! Frogged provided the answer which is easiest to understand at my level, but I will look up Abhay and Jan Markus answers too.
To learn more about lists in python https://www.studytonight.com/python/lists-in-python
#Easiest method - names =["Bulbasaur", "Ivysaur", "Venusaur", "Charmander", "Charmeleon", "Charizard", "Squirtle", "Wartortle", "Blastoise"] numbers = ["#1 ", "#2 ", "#3 ", "#4 ", "#5 ", "#6 ", "#7 ", "#8 ", "#9 "] pokedex = [] for i,j in zip(numbers,names): pokedex.append( i+' '+j)
g =[] for x in numbers: for i in names: if numbers.index(x) == names.index(i): g.append(x) g.append(i) print(g)