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 ?

2

2 Answers 2

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])
1
  • 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 3, 2017 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)
2
  • 1
    Do you mean list[i]?
    – mgilson
    Mar 3, 2017 at 18:03
  • Also, please don't use list as a variable name for a list. Mar 3, 2017 at 18:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.