Python program to print list elements in different ways

How to print python list elements :

Python list is used to hold same or different elements. All list elements are placed comma separated inside a square bracket []. You can access the list items and read/modify/delete them using index. The index starts from 0, i.e. 0 is the index of the first element, 1 is for the second element etc.

Similarly, you can use indices to print one sublist easily. In this post, I will show you different ways to print a list in python.

Using indices :

If you print the list variable, it will print all values in the list :

my_list = [1,2,3,4,5,6,7,8,9,10]

print(my_list)

It will print :

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

If you want to print only one part of the list, you can use indices :

list[first_index : last_index]

The first_index and last_index, both are optional. It returns one list from first_index to last_index, excluding last_index.

For example :

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print(my_list[:])
print(my_list[1:5])
print(my_list[:6])
print(my_list[6:])

It will print :

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]
[7, 8, 9, 10]
  1. The first statement prints all values because we are not providing first_index or last_index

  2. Second statement prints from index 1 to 4.

  3. The third statement prints from index 0 to 5.

  4. The fourth statement prints from index 6 to last.

Using * :

We can use * to print the list elements separated by a space :

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print(*my_list)

It will print :

1 2 3 4 5 6 7 8 9 10

You can also use one separator character :

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print(*my_list, sep = ',')

Output :

1,2,3,4,5,6,7,8,9,10

Using a for loop :

You can always traverse a list and print all items :

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for i in range(len(my_list)):
    print(my_list[i])

It will print all items in the list each on new line :

1
2
3
4
5
6
7
8
9
10

Similar tutorials :