1

I have a list of words.

mylist = ["aus","ausser","bei","mit","noch","seit","von","zu"]

I want to turn each element in the list into a sublist and add to each a number so that each entry is indexed. So it should output

[[1, 'aus'], [2, 'ausser'], [3, 'bei'], [4, 'mit'], [5, 'noch'], [6, 'seit'], [7, 'von'], [8, 'zu']]

I know how to do such a thing with a while loop

mylist = ["aus","ausser","bei","mit","noch","seit","von","zu","aus","ausser","bei","mit","noch","seit","von","zu","aus","ausser","bei","mit","noch","seit","von","zu"]

mylist2

i=0

while i <= 10:
    mylist2.append([i,mylist[i]])
    i = i +1

print(mylist2)

But I want to use the following kind of structure with a for-loop:

mylist = ["aus","ausser","bei","mit","noch","seit","von","zu"]

outlist =[[1,word] for word in mylist]
print(outlist)

I'm not sure how to do that with a for-loop. Can someone explain how to do this?

2
  • You could use enumerate: list(enumerate(mylist, 1)) Commented Feb 4, 2017 at 1:36
  • There is a reason people keep removing tags from your titles. Please stop writing them. Also don't use quote formatting for things that aren't quotes. Commented Feb 4, 2017 at 1:36

4 Answers 4

2

If you want the inner parts to be lists then you can cast the enumerate result to a list inside a list comprehension:

>>> mylist = ["aus","ausser","bei","mit","noch","seit","von","zu"]
>>> [[idx, item] for idx, item in enumerate(mylist, 1)]
[[1, 'aus'],
 [2, 'ausser'],
 [3, 'bei'],
 [4, 'mit'],
 [5, 'noch'],
 [6, 'seit'],
 [7, 'von'],
 [8, 'zu']]
Sign up to request clarification or add additional context in comments.

Comments

0

Use enumerate

>>> mylist = ["aus","ausser","bei","mit","noch","seit","von","zu"]
>>> list(enumerate(mylist, 1))

[(1, 'aus'),
 (2, 'ausser'),
 (3, 'bei'),
 (4, 'mit'),
 (5, 'noch'),
 (6, 'seit'),
 (7, 'von'),
 (8, 'zu')]

If you need a list of lists instead of tuples, you can do

list(map(list(enumerate(mylist, 1))))

or

[[number, word] for number, word in enumerate(mylist, 1)]

1 Comment

change ``` list(enumerate(mylist, 1) ``` to ``` list(enumerate(mylist, 1))```
0

Use enumerate:

[list(element) for element in list(enumerate(mylist, 1))]

1 Comment

You don't need the list in list(enumerate(mylist, 1)).
0

This is the method I think you are looking for.

list1 = ["aus","ausser","bei","mit","noch","seit","von","zu"]
list2 = []
for i in range(len(list1)):
    list2 += [[i+1, list1[i]]]
print (list2)

Uses a for loop to go through each item in list 1 and the indexes in list 1 and the adds 1 to the index so that it doesn't start with 0.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.