0

I am currently learning Python and I am struggling to display a specific amount of values from a list using for.

Here is an example of what I want to do in Java:

for(int i=0; i<=5; i++){
   System.out.println(list(i));
}

How can I write this code in python ?

Toms River
  • 196
  • 1
  • 4
  • 13

2 Answers2

2

You can use list slicing, which takes the notation of [start:end]

For example:

my_list = ['some', 'stuff', 'in', 'this', 'list', 'of', 'mine']
print(my_list[0:5])
Stacktrace
  • 112
  • 4
  • 1
    FWIW, if the start is `0` (or the end is the end of the list), it's common to leave them off: `my_list[:5]` or `my_list[2:]`. There's also an optional step: `my_list[:5:2]` – mgilson Mar 03 '17 at 18:03
1

Python is close in syntax to JavaScript, Java & C. Blocks are identified by tabs or spaces instead of braces. Range here is used to return an array consisting of 5 integers. Think of this loop as a for in loop (used to loop through object values in JS).

for i in range(5):
  print(yourCustomList[i])

If you want to loop through the index of a string or array substitute range() with range(len(array)).

Even better, you can just have Python loop through the values instead of the indexes.

for i in yourCustomList[:5]:
  print(i)