2

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.

  • 3
    your code seems incorrect because of the additional `]` you have after `hand[i]` – adir abargil Nov 15 '20 at 15:32
  • 1
    Does - [Understanding slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation) - answer your question? ... [https://docs.python.org/3/reference/expressions.html#slicings](https://docs.python.org/3/reference/expressions.html#slicings) – wwii Nov 15 '20 at 15:43
  • Makes so much sense, thanks! Andyes noted on the extra ] - I saw that afterwards –  Nov 15 '20 at 17:21

2 Answers2

4

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]])
L3viathan
  • 26,748
  • 2
  • 58
  • 81
0

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!!
LynxLike
  • 391
  • 5
  • 10