You can try list indexing:

data = [[6.0, 0.5], [6.1, 1.0], [6.2, 1.5], [6.3, 2.0], [6.4, 2.5], [6.5, 3.0], [6.6, 3.5], [6.7, 4.0], [6.8, 4.5]]
d1 = [item[0] for item in data]
print d1
d2 = [item[1] for item in data]
print d2

output :

[6.0, 6.1, 6.2, 6.3, 6.4, 6.5, 6.6, 6.7, 6.8]
[0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5]
Answer from Harsha Biyani on Stack Overflow
Discussions

In a Python list, how can I print the 1st and 2nd elements on a line, the 3rd and 4th on the next line, and so forth? - Stack Overflow
I am generating a string and appending it to a list. I am looping that action to make a list of 40 elements. I want to print them like so: here's my list list = [ 'first', 'second', 'third', ... ' More on stackoverflow.com
🌐 stackoverflow.com
How i print each second element in a list full of lines? Python - Stack Overflow
I have a list of numbers like this(saved in .txt file): list_of_numbers = [ ('5', 2.5, 5200), ('6', 3.2, 5236), ('8', 5.4, 5287), ('6', 8.7, 2563) ] And i imported this list (list is .... More on stackoverflow.com
🌐 stackoverflow.com
March 1, 2017
How do I access the 2nd item in a list?
Question How do I access the 2nd item in a list? Answer Recall that lists start counting from 0, not 1! So if we want to access an item, we start as 0 for the index of the first item, and count our way up to the item we want. In this case, we’re given a list n = [1, 3, 5], so the second element ... More on discuss.codecademy.com
🌐 discuss.codecademy.com
0
1
June 21, 2018
Result the second element of a list in python - Stack Overflow
I would like to use x as a variable for the first element and the result will be the second element of that list. ... Then print the second element. Can anyone help me on this? ... I suggest using raw_input instead of input, Python 2.X will call eval on the result of your input and you may ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Bobby Hadz
bobbyhadz.com › blog › python-get-second-element-of-tuple
Get the Nth element of a Tuple or List of Tuples in Python | bobbyhadz
Copied!list_of_tuples = [('a', 1, '!'), ('b', 2, '@'), ('c', 3, '#')] first = [tup[0] for tup in list_of_tuples] print(first) # 👉️ ['a', 'b', 'c'] second = [tup[1] for tup in list_of_tuples] print(second) # 👉️ [1, 2, 3] last = [tup[-1] for tup in list_of_tuples] print(last) # 👉️ ['!', '@', '#'] ... We used a list comprehension to get a new list that contains the Nth element of each tuple. List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition. On each iteration, we access the tuple element at the specific index and return the result. Python indexes are zero-based, so the first element in a tuple has an index of 0, the second an index of 1, etc.
Top answer
1 of 2
2

You missed the brackets. Try this:

p = [x[1] for x in list_of_numbers]

To print the values, you could use

print(', '.join([str(x) for x in p]))

You also need to change the way you load the data from the file

Full Code:

def parse(raw):
    data = []
    for line in raw.split("\n"):
        line = line.strip()
        # --> "('5', 2.5, 5200)"
        if line.startswith("(") and line.endswith(")"):
            d = line[line.index("(")+1 : line.index(")", -1)]
            # --> "'5', 2.5, 5200"
            d = d.split(",")
            data.append([])
            for i in d:
                i = i.strip()
                try:
                    i = float(i)
                except:
                    pass
                data[-1].append(i)
    return data


raw = open("list_of_numbers.txt").read()

list_of_numbers = parse(raw)

p = [x[1] for x in list_of_numbers]
# --> [2.5, 3.2, 5.4, 8.7]
print(', '.join([str(x) for x in p]))
# ---> 2.5, 3.2, 5.4, 8.7

I suggest using pickle. Storing and loading your data is easy as:

import pickle
data = ...
# store
file = open('data.txt', 'w')
pickle.dump(data, file)
file.close()
# load
file = open('data.txt', 'r')
data = pickle.load(file)
file.close()
2 of 2
0

Another option is to use numpy.ndarray.

import numpy as np
list_of_numbers = [
    ('5', 2.5, 5200),
    ('6', 3.2, 5236),
    ('8', 5.4, 5287),
    ]
list_of_numbers = np.array(list_of_numbers)
p = list_of_numbers[:,1]
print(p)
# outputs: ['2.5' '3.2' '5.4']

In addition, since you're reading data from a text file, your first list should contain only str. (I really don’t understand how you get mixed strings and numbers using the method you describe in your question.) To fix that, you can either:

  • use numpy.loadtxt,
  • convert to float when switching to a ndarray: `np.array(list_of_numbers, dtype=float).

Finally, I strongly suggest that you learn about slices in Python.

🌐
Codecademy Forums
discuss.codecademy.com › frequently asked questions › python faq
How do I access the 2nd item in a list? - Python FAQ - Codecademy Forums
June 21, 2018 - Question How do I access the 2nd item in a list? Answer Recall that lists start counting from 0, not 1! So if we want to access an item, we start as 0 for the index of the first item, and count our way up to the item we want.
Find elsewhere
🌐
Quora
quora.com › How-do-I-print-nth-elements-in-the-list-simultaneously-in-Python
How to print nth elements in the list simultaneously in Python - Quora
Python (programming langu... ... Print the n-th elements of multiple lists “simultaneously” typically means: for a collection of sequences, extract element at index n from each sequence (handling out-of-range and differing lengths).
🌐
IncludeHelp
includehelp.com › python › print-list-elements-in-different-ways.aspx
Python program to print list elements in different ways
June 21, 2023 - # python program to demonstrate example of lists # declaring & initializing two list list1 = ["Amit", "Abhi", "Radib", 21, 22, 37] list2 = [100, 200, "Hello", "World"] print (list1) # printing complete list1 print (list1[0]) # printing 0th (first) element of list1 print (list1[0], list1[1]) # printing first & second elements print (list1[2:5]) # printing elements from 2nd to 5th index print (list1[1:]) # printing all elements from 1st index print (list2 * 2) # printing list2 two times print (list1 + list2) # printing concatenated list1 & list2
🌐
TutorialsPoint
tutorialspoint.com › article › How-to-get-the-second-to-last-element-of-a-list-in-Python
How to get the second-to-last element of a list in Python?
February 20, 2020 - fruits = ['apple', 'banana', 'cherry', 'date'] second_last = fruits[len(fruits) - 2] print(second_last) ... Use list[-2] for the second-to-last element.
🌐
Quora
quora.com › How-do-you-print-objects-in-specific-index-numbers-in-lists-in-python
How to print objects in specific index numbers in lists in python - Quora
Answer (1 of 2): your_list = [1, 2, 3] print("Hello number, " + your_list[0]) » Hello number, 1. Formula: item number on list -1 So, item number 2 on your_list is in position 1.
🌐
ItSolutionstuff
itsolutionstuff.com › post › python-get-second-last-element-of-list-exampleexample.html
Python Get Second Last Element of List Example - ItSolutionstuff.com
October 30, 2023 - In this example, I will create a simple list with the day with the name. Then I will get second last element with name using -2 key of array. so let's see the below example. You can use these examples with python3 (Python 3) version. ... myList = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] # Get Last Element lastElem = myList[-2] print(lastElem)
🌐
Bobby Hadz
bobbyhadz.com › blog › python-print-specific-items-in-list
How to Print specific items in a List in Python | bobbyhadz
The slice list_of_lists[0][1] returns the second element of the first sublist. I've also written an article on how to print a list in columns.
Top answer
1 of 2
2

You're getting this error because you try to access the second element of an array that contains only 1 string. In this case you want to check the length of the array

for line in open("testing.txt"):
   strip = line.rstrip()
   words = strip.split(';')
   for test in words:
      if len(words) > 1:
         print(words)
      else: # this else is not necessary
         continue

Edit: If you want to print each sentences containing at least one ';' only once, you don't actually have to use a for loop. One concise way to get the desired output would be this:

for line in open("testing.txt"):
    strip = line.rstrip()
    words = strip.split(';')
    if len(words) > 1:
        print(words)
2 of 2
0

As far as I understand from your question you only trying to print the words list which has more than one element.

One simple way to do it is:

    for line in open("testing.txt"):
       strip = line.rstrip()
       words = strip.split(';')
       # first = words[0]
       for test in words:
          if len(words) > 1:
             print(words)

Here you are just checking if the length of the words is greater than 1 and printing if that is the case

EDIT: I think the for loop is unnecessary. All you want is to print lists of words greater than length 1. So for that purpose:

    for line in open("testing.txt"):
       strip = line.rstrip()
       words = strip.split(';')
       if len(words) > 1:
          print(words)

Here you are just splitting the sentences on ; and then checking after splitting if the length of the list (named words) is greater than 1; if so you are printing the list named words.

EDIT2: As S3DEV had pointed out that you are opening a file inside for keyword which won't close your file automatically once you are out of for loop. As a result the file pointer remains open until the program stopped completely and it might cause weird issues. The best practice is to use with keyword. the with keyword automatically opens the file nad closes it once the block execution is complete, so you won't face any odd issues. form keeping a file pointer open.

    with open("testing.txt", "r") as f: # this line open file as f in read-only format
       for line in f:
          strip = line.rstrip()
          words = strip.split(';')
          if len(words) > 1:
             print(words)
🌐
Java2Blog
java2blog.com › home › python › python list › get every other element in list in python
Get Every Other Element in List in Python - Java2Blog
October 4, 2022 - The following code uses the enumerate() function along with list comprehension to get every other element in a list in Python. Using the enumerate() function along with list comprehension ... A lambda function is an anonymous function that is capable of holding a single expression while taking ...