How to call for information from a list?

Viewed 87

I'm quite new to Python and I would like some help. I'm currently trying to store information from the first line of a txt file in a tuple and I am having some trouble. The txt file's second line is:

Water: 0 0 4 2 1 3

I want to store the numbers only so my current code is:

water = []
with open(file_name) as f:
    lines = f.readlines()
    water_values = lines[1].strip()
    splitted = water_values.split(" ")
    splitted.remove("Water:")
    water.append(splitted)

However, when I call for water[1], expecting to receive 0, I find that the index is out of range and that the len(water) is only 1. When I print it, it says:

[['0', '0', '4', '2', '1', '3']]

How can I change it so that I can call for each element?

3 Answers

When you call water.append(splitted) you are adding a new element to the end of the list and splitted is a list so you get a list of lists.

If you want to combine two lists, you should instead call water += splitted. The += operator means that you are adding to the left side value, what ever is on the right side and is analogous to water = water + splitted.

You should use .extend rather than .append, i.e. instead of

water.append(splitted)

do

water.extend(splitted)

Simple example to show difference:

a = []
b = []
a.append([1,2,3])
b.extend([1,2,3])
print(a)
print(b)

output:

[[1, 2, 3]]
[1, 2, 3]

If you know to want more about handling lists in python read More on Lists in docs

your code water.append(splitted) just adds splitted (which is a list) as a first element of water list. To add values from splitted you could just do following: water += splitted instead of water.append(splitted)

Doing so - you will get water = ['0', '0', '4', '2', '1', '3'].

You can read more here How do I concatenate two lists in Python?

Related