I'm making a little data base on python.
my_list = ['jack', 'liam', 'gary', 'poly']
I want to convert the list into this
result = [('jack', 'liam'),('liam', 'gary'),('gary', 'poly')]
Is there anyway i can do this?
I'm making a little data base on python.
my_list = ['jack', 'liam', 'gary', 'poly']
I want to convert the list into this
result = [('jack', 'liam'),('liam', 'gary'),('gary', 'poly')]
Is there anyway i can do this?
Use list comprehension
my_list = ['jack', 'liam', 'gary', 'poly']
new_list = [(my_list[i],my_list[i+1]) for i in range(len(my_list)-1)]
print(new_list)
>> [('jack', 'liam'), ('liam', 'gary'), ('gary', 'poly')]
Or Use zip()
which will return consecutive combinations as tuple.
my_list = ['jack', 'liam', 'gary', 'poly']
new_list = list(zip(my_list, my_list[1:]))
print(new_list)
>> [('jack', 'liam'), ('liam', 'gary'), ('gary', 'poly')]
zip will return a tuple from two iterables; if you take the same list, but shifted as you wish (in this case, one element forward) you can have your expected result.
Also, the generator will exhaust on the shortest iterable (the second one).
>>> [(a,b) for (a,b) in zip(my_list, my_list[1:])]
[('jack', 'liam'), ('liam', 'gary'), ('gary', 'poly')]
list(zip(my_list, my_list[1:])) will work the same.