unknown
unknown

Reputation: 31

Can anyone explain how list = [[] for _ in range(vertex)] works?

Looks like it prints out something like [[], [], []].

could someone rephrase it without using list comprehension?

Upvotes: 0

Views: 2001

Answers (2)

johnashu
johnashu

Reputation: 2211

Without list comprehension it would simply be

is_weighted = False 
is_directed = False 
graph_list = graph_str.splitlines() 
num_verticies = int(graph_list[0].split()[1]) 
graph_list.pop(0)

adj_list = [] #create an empty list to append to

for x in range(num_verticies): #start the for loop
    adj_list.append([]) #append an empty list the num_vertices times

print(adj_list)

Upvotes: 1

metamemelord
metamemelord

Reputation: 528

You are creating a list of empty lists of size vertex. These are called list comprehensions.

For ex:

foo = [i for i in range(10)]
print(foo)

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Read more https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions.

Also, post complete code next time for others to comprehend and help you.

Upvotes: 2

Related Questions