+ 6

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?

18th Jan 2021, 6:30 PM
Peter
Peter - avatar
9 Respostas
+ 7
print([i[0]+i[1] for i in zip(numbers,names)])
18th Jan 2021, 6:36 PM
Abhay
Abhay - avatar
+ 7
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.
18th Jan 2021, 6:56 PM
Oma Falk
Oma Falk - avatar
+ 3
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)]
18th Jan 2021, 8:42 PM
Benjamin Jürgens
Benjamin Jürgens - avatar
+ 3
schaust halt, welche du nimmst. servus und gruss von der Waterkant.
18th Jan 2021, 8:45 PM
Oma Falk
Oma Falk - avatar
+ 2
Looks like you used nested loops, which gave you every possible combination, but just a single loop is needed here
18th Jan 2021, 8:45 PM
Benjamin Jürgens
Benjamin Jürgens - avatar
+ 1
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.
18th Jan 2021, 8:20 PM
Peter
Peter - avatar
19th Jan 2021, 10:44 AM
Sagar Maurya
Sagar Maurya - avatar
0
#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)
20th Jan 2021, 7:34 AM
Surkhab Khan
Surkhab Khan - avatar
- 1
g =[] for x in numbers: for i in names: if numbers.index(x) == names.index(i): g.append(x) g.append(i) print(g)
20th Jan 2021, 1:08 PM
madeline
madeline - avatar