0

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?

assda
  • 3
  • 1
  • 1
    See this post https://stackoverflow.com/questions/11487049/python-list-of-lists, seems quite relevant. –  Jun 03 '21 at 10:27
  • Or perhaps this post could help too? https://stackoverflow.com/questions/6614891/turning-a-list-into-nested-lists-in-python – Party-with-Programming Jun 03 '21 at 10:28

5 Answers5

1

Use list comprehension

  • Iterate till second last value of the list
  • get current and next value as a tuple.
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')]
Hamza usman ghani
  • 2,264
  • 5
  • 19
0

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')]
crissal
  • 2,547
  • 7
  • 25
0
my_list = ['jack', 'liam', 'gary', 'poly']

result_list = [(my_list[i],my_list[i+1]) for i in range(len(my_list) - 1)]

print(result_list)

Output

[('jack', 'liam'), ('liam', 'gary'), ('gary', 'poly')]

We can fetch 2 elements into a tuple till we iterate and reach the second last element.

Stan11
  • 274
  • 3
  • 11
0
result = []
my_list = ['jack', 'liam', 'gary', 'poly']
for i, item in enumerate(my_list):
   if i+1 == len(my_list): break
   result.append((item, my_list[i+1]))

Or more Pythonic and elegant way:

result = [(item, my_list[i+1]) for i, item in enumerate(my_list) if i+1 < len(my_list)] 
AmineBTG
  • 597
  • 3
  • 13
0
my_list = ['jack', 'liam', 'gary', 'poly']
result = []
for i in range(0, len(my_list)):
    if not i > len(my_list)-2:
        result.append((my_list[i], my_list[i+1]))

output

[('jack', 'liam'), ('liam', 'gary'), ('gary', 'poly')]
williamr21
  • 147
  • 7