Stan Shunpike
Stan Shunpike

Reputation: 2234

How to index a list using for loops?

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?

Upvotes: 1

Views: 112

Answers (4)

R. Mercy
R. Mercy

Reputation: 509

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.

Upvotes: 0

Azeem Ghumman
Azeem Ghumman

Reputation: 71

Use enumerate:

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

Upvotes: 0

H&#229;ken Lid
H&#229;ken Lid

Reputation: 23064

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)]

Upvotes: 0

MSeifert
MSeifert

Reputation: 152587

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']]

Upvotes: 2

Related Questions