How do i print a specific item in a list python?

I'm wondering how to print specific items from a list e.g. given:

li = [1,2,3,4]

I want to print just the 3rd and 4th within a loop and I have been trying to use some kind of for-loop like the following:

for i in range (li(3,4)):
    print (li[i])

However I'm Getting all kinds of error such as:

TypeError: list indices must be integers, not tuple.
TypeError: list object is not callable

I've been trying to change () for [] and been shuffling the words around to see if it would work but it hasn't so far.

How do i print a specific item in a list python?

asked Dec 16, 2013 at 11:06

Using slice notation you can get the sublist of items you want:

>>> li = [1,2,3,4]
>>> li[2:]
[3, 4]

Then just iterate over the sublist:

>>> for item in li[2:]:
...     print item
... 
3
4

answered Dec 16, 2013 at 11:09

How do i print a specific item in a list python?

Chris SeymourChris Seymour

81k29 gold badges153 silver badges194 bronze badges

You should do:

for i in [2, 3]:
    print(li[i])

By range(n), you are getting [0, 1, 2, ..., n-1]

By range(m, n), you are getting [m, m+1, ..., n-1]

That is why you use range, getting a list of indices.

It is more recommended to use slicing like other fellows showed.

answered Dec 16, 2013 at 11:09

RayRay

2,46217 silver badges21 bronze badges

3

li(3,4) will try to call whatever li is with the arguments 3 and 4. As a list is not callable, this will fail. If you want to iterate over a certain list of indexes, you can just specify it like that:

for i in [2, 3]:
    print(li[i])

Note that indexes start at zero, so if you want to get the 3 and 4 you will need to access list indexes 2 and 3.

You can also slice the list and iterate over the lists instead. By doing li[2:4] you get a list containing the third and fourth element (i.e. indexes i with 2 <= i < 4). And then you can use the for loop to iterate over those elements:

for x in li[2:4]:
    print(x)

Note that iterating over a list will give you the elements directly but not the indexes.

answered Dec 16, 2013 at 11:12

pokepoke

348k66 gold badges536 silver badges581 bronze badges

Explore endless possibilities of printing and formatting lists in Python

Python’s list data structure is built for simplicity and flexibility. We are going to have a look at how anyone can leverage lists as an essential tool for automation and sailing through tedious tasks.

I’ll be showing several different techniques for printing a list in Python. I’ll cover the basics of printing a list using Python’s built-in print() method, printing a list using loops, as well as some neat formatting tricks such as printing a list on multiple lines.

Don't feel like reading? Watch my video instead:


What is a List in Python?

One of the most important features of any programming language is the ability to define variables. Variables allow the programmer to store information, like numbers or strings of text, and reuse it efficiently. This is part of what makes computers such terrific tools; we can feed them a bunch of information, and they can remember it and manipulate it way more easily than humans can.

Like variables, Python lists also store information. More specifically, they store sequences of information. This is not unlike analog lists that you may be familiar with. If a person wants to store a sequence of to-do’s so they’ll remember them throughout the day, they may write a to-do list. Grocery lists are another example.

While array and list structures in some programming languages require learning funky syntax and have strict rules about what data types they can hold, Python lists have none of that! This makes them super simple to use and equally flexible. Now we’ll take a look at how to define lists and access the information within them. Check it out:

my_list = ['pizza', 'cookies', 'soda']

Here, I have defined a list called my_list whose elements strings, but the elements of a list can also be numbers like integers and floats, other lists, or a mix of different types. You might think about this list as representing the items on a grocery list and the quantities I want to buy.

If I want to access any of this information specifically, I would use a technique called list indexing. With list indexing, one simply puts the number (starting with 0) of the element one wishes to access in square braces following the name of the list. For instance, if I want to print the first and third elements of my_list, I would use the following code:

print(my_list[0], my_list[2])

Output:

How do i print a specific item in a list python?
Image 1 - Printing individual list elements in Python (image by author)

Notice how I use the indices 0 and 2 to represent the first and third elements since Python indexing begins with 0.

Now, that’s certainly useful, but you might be wondering how any of this is more efficient than working with normal variables. After all, we had to specify each element we wanted to print individually in the example above.

Next up, I am going to show you how you can start to leverage some of Python’s other built-in features to access information in lists much more efficiently.


Perhaps one of the most intuitive ways to access and manipulate the information in a list is with a for loop. What makes this technique so intuitive is that it reads less like programming and more like written English!

Imagine you want to describe your intention of buying the items on your grocery list to a friend. You might say something like, “For each item in my grocery list, I want to buy this quantity”. You can write almost the same thing in Python to loop through your Python list. Let’s print some formatted strings based on the contents of our Python list!

for element in my_list:
    print(f"I bought {element}!")

Output:

How do i print a specific item in a list python?
Image 2 - Printing a Python list in a for loop (image by author)

Here, you can see that I was able to loop through each element of my list without having to specify each element manually. Imagine how much work this would save if your list had 50,000 elements instead of just three!

You can also loop through a list using a for loop in conjunction with the built-in Python range() method:

for element in range(len(my_list)):
    print(f"I bought {my_list[element]}!")

The output here is the same, but instead of element referring to an actual element in our list as it did in the previous example, element now refers to the index position. We use list indexing again to access the element at the location specified by element.

Now, we are getting somewhere. Hopefully, you can see that Python provides some great tools for accessing sequences of information stored in lists. Let’s take a look at some other ways to print Python lists!


Use * Operator to Print a Python List

Another way to print all of the contents of a list is to use the * or "splat" operator. The splat operator can be used to pass all of the contents of a list to a function. For instance, the built-in Python method print() can print a Python list element-by-element when fed the name of the list preceded by the splat operator.

Let’s see what that looks like in code:

print(*my_list)

Output:

How do i print a specific item in a list python?
Image 3 - Printing a Python list with the * operator (image by author)

It’s that simple!


If you want a technique that’s even easier to use than that, you can simply pass the name of the list to the print() method by itself! You should note that the output will look a little bit different in this case. See if you can spot the difference:

print(my_list)

Output:

How do i print a specific item in a list python?
Image 4 - Printing a Python list with the print() method (image by author)

The output in this case is a bit more "raw". We still have the square brackets around the list and the quotation marks around each element.


Yet another way to print the elements of a list would be to use the Python built-in map() method. This method takes two arguments: a function to apply to each element of a list and a list. Here, we will pass print as our function to apply to each of the elements, and we will pass my_list as our list. Additionally, map() returns a map object, so we have to turn the result into a list for the elements to print properly.

list(map(print, my_list))

Output:

How do i print a specific item in a list python?
Image 5 - Printing a list with the map() method (image by author)

You can ignore the [None, None, None] in the output. This is simply referring to the fact that the print() method doesn’t return any values. It just prints!


Another handy way to print a Python list is to use the join() method. join() is a string method, meaning that it has to be called on a string. We will see what this means in a moment. With this method, you can specify a delimiter that will go in between each element in the list when they are all printed out. If it sounds complicated, I’m sure the code snippet will make it clear.

print(' '.join(my_list))

Output:

How do i print a specific item in a list python?
Image 6 - Printing a Python list with the join() method (image by author)

You can see in the code that we are using our good friend, the print() method, to print the list. What’s different is that we start by specifying a string. In this case, the string is just a space. Then, as I mentioned before, we call the string method join() on this string, and we pass it in our list. This effectively joins each element of our list and connects them with a space. We print this result out, and the output is reminiscent of the output of some of the previous methods at which we’ve already looked.


As I mentioned in the last section, we can also use the join() method to print out our list with a custom delimiter or separator. The only change we need to make to the code in the last example is to change the string on which we call join(). We used a space in the first example, but you can use any string! Here, we will use the string " I like " (notice the spaces at the beginning and end).

print(' I like '.join(my_list))

Output:

How do i print a specific item in a list python?
Image 7 - Printing a list with a custom separator (image by author)

You can see that instead of joining our list elements with a space, we instead join them together with our custom separator " I like ". This is useful when you want to create CSV or TSV (comma-separated or tab-separated value) files. These are very common formats in data science applications. You would simply need to specify a "," or "\t" as your separator string.


Advanced: How to Print a List Vertically in Python?

There are some advanced use cases in which you might have a list of lists, and you want to print list items vertically. It's easy to do with a single list, but not so intuitive with more complex data structures.

Examine the following list - it contains three lists, each representing a score by three students on the test (3 tests in total):

test_scores = [[91, 67, 32], [55, 79, 83], [99, 12, 49]]

To get scores of the first student, we could access the elements with the following syntax:

test_scores[0][0], test_scores[1][0], test_scores[2][0]

But that's tedious to write and isn't scalable. Instead, we could use two for loops - the first one to grab the three lists, and the second one to grab individual list items. You can then call the print() method with the custom ending character. Don't forget to call the print() method once again at the same indentation level as the first loop - otherwise, all elements will be printed on the same line:

for i in range(len(test_scores)):
    for j in test_scores:
        print(j[i], end=' ')
    print()

Output:

How do i print a specific item in a list python?
Image 8 - Printing Python lists vertically (image by author)

You can further simplify the syntax by using the zip() method:

for t1, t2, t3 in zip(*test_scores):
    print(t1, t2, t3)

The output is identical, but the code is significantly shorter.


Conclusion

I hope after these examples that you have a better understanding of the myriad ways that Python offers to access the information stored within a Python list. These techniques give the programmer tons of control over the formatting, and with a little know-how, you can get the resulting output that you want in as little as one line of code! Python does an exceptional job making tasks like this incredibly simple, and, at times, as easy as writing in English.

Make sure to stay tuned for more in-depth Python tutorials!

  • 5 Best Books to Learn Data Science Prerequisites (Math, Stats, and Programming)
  • Top 5 Books to Learn Data Science in 2022
  • How to Install Apache Airflow Locally

Stay connected

  • Hire me as a technical writer
  • Subscribe on YouTube
  • Connect on LinkedIn

How do you print a specific item in a list Python?

Without using loops: * symbol is use to print the list elements in a single line with space. To print all elements in new lines or separated by space use sep=”\n” or sep=”, ” respectively.

How do you print elements of a list in a single line in Python?

When you wish to print the list elements in a single line with the spaces in between, you can make use of the "*" operator for the same. Using this operator, you can print all the elements of the list in a new separate line with spaces in between every element using sep attribute such as sep=”/n” or sep=”,”.

How do you print part of an array in Python?

STEP 1: Declare and initialize an array. STEP 2: Loop through the array by incrementing the value of i. STEP 3: Finally, print out each element of the array.

How do you take one element from a list?

There are three ways in which you can Remove elements from List: Using the remove() method. Using the list object's pop() method. Using the del operator.