what comes before "for i in range (...)"

Viewed 82

I have a simple question, looking at the following code:

 letters = [hand[i]][:1] for i in range(5)]

What does the argument before 'for I in range(5)' do?? I can't seem to figure it out.

2 Answers

A simple list comprehension has three parts:

my_list = [A for B in C]

This translates exactly into:

my_list = []
for B in C:
    my_list.append(A)

So the part before for determines what goes into the list you're creating.


In your case, you could also write it like this:

letters = []
for i in range(i):
    letters.append(hand[i][:1]])

The upper piece of code is called list comprehension:

https://docs.python.org/3/tutorial/datastructures.html

So the upper code could be explicitly written out as:

hand # some data. From your code it should be a nested list, eq: hand = [ [...],[...],... ]
letters = []
for i in range(5): # iterates trough 0-4
    element = hand[i][:1] 
    letters.append(element)

So this is just a very short way of constructing a list. You read it out lout like so: For every i from range(5) take element(s) hand[i][:1] and assign it to a new list letters.

If your question is about the part hand[i][:1], then this is a slice from a nested list. For example:

hand = [
  [0,1,2,3],
  [4,5,6,7],
  ...
]

hand[0] == [0,1,2,3]
hand[0][:1] == [0]
hand[1][:1] == [4] # mind it is a slice, so you are left with a list!!
Related