Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I want to iterate it through the Python (3.8.5) list and append two items at a time into a list of lists. The source list will always contain an even number of an element.

example output:

[['a','b'],['c','d']['e','f'],['g','h']]

I have tried range function, for loop, while loop, etc. I am seeking an eloquent, efficient way to do it. Below are the two incorrect pathways I have explored using the example data. 

letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']

letter_pairs = []

count = 0

for i in range(2): 

    for letter in letters:

        letter_pairs.append([letter, letter])

while count < 2:

   for letter in letters:

       letter_pairs.append([letter, letter])

       count += 1

1 Answer

0 votes
by (36.8k points)

Use the zip:

[list(x) for x in zip(letters[:-1:2], letters[1::2])]

 Want to be a master in Data Science? Enroll in this Data Scientist

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Apr 29, 2020 in Data Science by blackindya (18.4k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...