2

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?

  • 2
    Did you mean `water_values = lines[0].strip()` ? Notice the `0` instead of `1`. – Ashok Arora May 24 '21 at 07:24
  • @AshokArora No, I believe lines[1] should be correct. That is the first line of the txt file. –  May 24 '21 at 07:28
  • 1
    @AnonymousUser Python, like many other programming languages start indexing at 0, so the 0 index, gives you the first item in a list (or a file). This gives the basic explanation with some additional tips and tricks: https://towardsdatascience.com/the-basics-of-indexing-and-slicing-python-lists-2d12c90a94cf – Tzane May 24 '21 at 07:31

3 Answers3

1

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.

Tzane
  • 2,752
  • 1
  • 10
  • 21
  • Ohh, I see. Thanks! But how do I change the elements in the list from string back into integers? –  May 24 '21 at 07:37
  • @AnonymousUser You can find lot of different ways here: https://stackoverflow.com/questions/7368789/convert-all-strings-in-a-list-to-int – Tzane May 24 '21 at 07:40
1

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

Daweo
  • 31,313
  • 3
  • 12
  • 25
1

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?

Artsiom
  • 197
  • 1
  • 9