What's the proper way to use List?

Anytime I use List, I hit issues with Reference. Looking through docs, I see that Reference is related to unsafe memory operations. I'm looking into how to avoid variable-length collections using parameters, but I'd like to get this working first, at least. Any ideas?
from collections import List

fn main():
var my_list: List[Int] = List(1, 2, 3)
for member in my_list:
for i in range(member):
# failed to infer parameter 'type', argument type 'Reference[Int, 1, my_list]' does not conform to trait 'IntableRaising'
print("counting: " + i)
from collections import List

fn main():
var my_list: List[Int] = List(1, 2, 3)
for member in my_list:
for i in range(member):
# failed to infer parameter 'type', argument type 'Reference[Int, 1, my_list]' does not conform to trait 'IntableRaising'
print("counting: " + i)
Edit: I tried adding a var count: Int = member.value in there but to no avail.
3 Replies
TheBeege
TheBeege4mo ago
it's gross, but i've answered my own question. i found the example here: https://docs.modular.com/mojo/manual/traits#generic-structs-with-traits looks like List doesn't support direct iteration, but it does support Python-style accessing. this works:
from collections import List

fn main():
var my_list: List[Int] = List(1, 2, 3)
for i in range(len(my_list)):
for j in range(my_list[i]):
print("counting: ", j)
from collections import List

fn main():
var my_list: List[Int] = List(1, 2, 3)
for i in range(len(my_list)):
for j in range(my_list[i]):
print("counting: ", j)
Ryulord
Ryulord4mo ago
the list iterator doesn't directly give you the items in the list, it gives you references to the items in the list. To get the actual item you need to index into the reference. References only contain 1 thing so you don't need to actually pass an index.
var my_list: List[Int] = List(1, 2, 3)
for item in my_list:
# type of item is Reference[Int]
# type of item[] is Int
print(item[])
var my_list: List[Int] = List(1, 2, 3)
for item in my_list:
# type of item is Reference[Int]
# type of item[] is Int
print(item[])
TheBeege
TheBeege4mo ago
okay, cool. that'll work. thank you!